我已经尝试过 Google Results、Stackoverflow 和 AutoMapper 中的大部分示例。但无法让 IValueResolverdependancy 注入工作。
我有以下服务
public class StorageService : IStorageService
{
private readonly BlobServiceSettings _blobServiceSettings;
public StorageService(IOptions<BlobServiceSettings> blobServiceSettings)
{
_blobServiceSettings = blobServiceSettings.Value;
}
// some methods I need
}
这是我的个人资料
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Building, BuildingEnvelope>(MemberList.None)
.ForMember(dest => dest.ImageUrl, opt => opt.ResolveUsing<BuildingImageUrlResolver>());
}
}
这是我的 IValueResolver
public class BuildingImageUrlResolver : IValueResolver<Building, BuildingEnvelope, string>
{
private readonly IStorageService _storageService;
public BuildingImageUrlResolver(IStorageService storageService)
{
_storageService = storageService;
}
public string Resolve(Building entity, BuildingEnvelope envelope, string member, ResolutionContext context)
{
return _storageService.MyMethod(entity.ImageFileName);
}
}
我在内部异常中收到以下错误
No parameterless constructor defined for this object.
不确定我做错了什么。
提前致谢
尼奥
卢锡安的建议是正确的——AutoMapper.Extensions.Microsoft.DependencyInjection https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection包是要走的路。即使您不想使用它,也必须执行类似的操作。
我遇到了同样的问题,通过使用扩展,您只需修改注册 AutoMapper 及其配置的入口点即可。
扩展程序的作用(source https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection/blob/191acb94a6c21163339d5d0b81bb0f2c19efab2b/src/AutoMapper.Extensions.Microsoft.DependencyInjection/ServiceCollectionExtensions.cs#L72) is:
- 使用提供的配置初始化 Automapper
-
它扫描您拥有的可以通过依赖注入实现的所有类,并将它们注册为瞬态,查找以下内容的实现:
IValueResolver
IMemberValueResolver
ITypeConverter
IMappingAction
它将扫描的程序集实际上取决于您在调用时提供的参数。
- 如果其中任何一个可以实际实例化,那么它们将被注册为临时实现。
- 就像这样,AutoMapper 将向服务提供商请求这些实例,服务提供商将解析它们,为此,它还将解析任何待处理的依赖项。
请注意,这实际上非常简单——最困难的部分是扫描正确的程序集并注册正确的类。您也可以手动执行此操作,但这些扩展已经为您处理好了。
请注意,即使反射已经得到很大改进,这个过程也相对较慢,所以尽量不要过度滥用它(例如,在测试中)。
最后,如果这些都不适合您,请记住您还需要设置 AutoMapper 才能使用依赖项注入解析器:
automapperConfiguration.ConstructServicesUsing(serviceProvider.GetService);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)