我已经尝试了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.
不确定我做错了什么。
在此先感谢Neo
Lucian的建议是正确的 - AutoMapper.Extensions.Microsoft.DependencyInjection
包是要走的路。即使你不想使用它,你也必须做类似的事情。
我遇到了同样的问题,通过使用扩展,您只需修改注册AutoMapper及其配置的入口点。
扩展的功能(source)是:
IValueResolver
IMemberValueResolver
ITypeConverter
IMappingAction
它将扫描的程序集实际上取决于您在调用时提供的参数。请注意,这实际上非常简单 - 最困难的部分是扫描正确的程序集并注册正确的类。你也可以手动完成,但这些扩展已经为你完成了。
请注意,即使反射得到了很大改善,这个过程相对较慢,所以尽量不要滥用它(例如,在测试中)。
最后,如果这些都不适合您,请记住您还需要设置AutoMapper以使用依赖注入解析器:
automapperConfiguration.ConstructServicesUsing(serviceProvider.GetService);