我收到一個(gè)錯(cuò)誤:AutoMapper v11.0.1
無(wú)法創(chuàng)建自定義IMemberValueResolver
類型的實(shí)例。
這是我的自定義解析器:
public class FooCollectionResolver<TModel, TViewModel> : IMemberValueResolver<object, object, BlockListModel?, IEnumerable<TViewModel>?>
where TModel : class, IPublishedElement
where TViewModel : class
{
public IEnumerable<TViewModel>? Resolve(object source, object destination, BlockListModel? sourceMember, IEnumerable<TViewModel>? destMember, ResolutionContext context)
{ }
}
它接受源BlockListModel
成員并返回TViewModel
的集合。
Example usage:
this.CreateMap<FooModel, FooViewModel>().ForMember(
dest => dest.BlockListModelMember,
src => src.MapFrom<FooCollectionResolver<FooCollectionModel, FooCollectionViewModel>, BlockListModel>(s => s.BlockListModelMember));
FooModel.cs:
public class FooModel
{
public string Title { get; set; }
public BlockListModel BlockListModelMember { get; set; }
}
FooViewModel.cs
public class FooViewModel
{
public string Title { get; set; }
public IEnumerable<FooCollectionViewModel> BlockListModelMember { get; set; }
}
FooCollectionModel.cs
public class FooCollectionModel
{
public string FooMember { get; set; }
}
FooCollectionViewModel.cs
public class FooCollectionViewModel
{
public string FooMember { get; set; }
}
DI的注冊(cè)方式如下:
services.AddAutoMapper(cfg =>
{
cfg.AddMaps(new[]
{
"FooNamespace.Web",
"FooNamespace.Web.Framework",
});
});
此特定映射配置文件包含在FooNamespace.Web
中。此配置文件中的任何其他地圖都沒(méi)有問(wèn)題。
AutoMapper
拋出一個(gè)錯(cuò)誤,它無(wú)法在運(yùn)行時(shí)創(chuàng)建FooCollectionResolver
的實(shí)例。我相信它試圖在使用泛型.MapFrom<T>
方法時(shí)通過(guò)反射創(chuàng)建實(shí)例。
Exception:
AutoMapperMappingException:無(wú)法創(chuàng)建GPE.Web.Framework.Mapping.ValueResolvers.FooCollectionResolver`2[FooCollectionModel,FooCollectionViewModel]類型的實(shí)例
AutoMapper.ResolutionContext.CreateInstance(Type type)
AutoMapperMappingException:映射類型時(shí)出錯(cuò)。
映射類型:FooModel->FooViewModel
類型映射配置:FooModel->FooViewModel
Destination Member: BlockListModelMember
有人知道這是為什么嗎?
我可以使用內(nèi)聯(lián)解析函數(shù)e.g實(shí)現(xiàn)這一點(diǎn):
this.CreateMap<FooModel, FooViewModel>()
.ForMember(
dest => dest.BlockListModelMember,
src => src.MapFrom((src, dest, destMember, context) =>
{
// mapping logic
}));
但是我想重用這個(gè)邏輯,因?yàn)樗菓?yīng)用于不同模型的相同的通用模式,因此泛型IMemberValueResolver
當(dāng)您使用
services.AddAutoMapper
的特定重載時(shí),它不會(huì)將值解析程序添加到容器中。您可以改用此方法,它將掃描程序集以查找所有相關(guān)類型:如果您查看AddAutoMapperClasses的實(shí)現(xiàn),這是
AddAutoMapper
擴(kuò)展方法最終調(diào)用的內(nèi)容,您會(huì)發(fā)現(xiàn),如果它傳遞了assembliesToScan
的集合,它只注冊(cè)IMemberValueResolver
類型(以及其他類型)。您正在使用的重載傳遞了該參數(shù)
null
,因此它們不會(huì)被注冊(cè)。