I have tried most of the examples in the Google Results, Stackoverflow and in AutoMapper. But was not able to get the IValueResolverdependancy injection to work.
I have below service
public class StorageService : IStorageService
{
private readonly BlobServiceSettings _blobServiceSettings;
public StorageService(IOptions<BlobServiceSettings> blobServiceSettings)
{
_blobServiceSettings = blobServiceSettings.Value;
}
// some methods I need
}
This is my profile
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Building, BuildingEnvelope>(MemberList.None)
.ForMember(dest => dest.ImageUrl, opt => opt.ResolveUsing<BuildingImageUrlResolver>());
}
}
this is my 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);
}
}
I get the below error in my inner exception
No parameterless constructor defined for this object.
Not sure what I am doing wrong.
Thanks in advance Neo
答案 0 :(得分:0)
Lucian的建议是正确的 - AutoMapper.Extensions.Microsoft.DependencyInjection
包是要走的路。即使你不想使用它,你也必须做类似的事情。
我遇到了同样的问题,通过使用扩展,您只需修改注册AutoMapper及其配置的入口点。
扩展程序的作用是什么(source):
它会扫描您可以通过依赖注入实现的所有类,并将它们注册为瞬态,查找以下实现:
IValueResolver
IMemberValueResolver
ITypeConverter
IMappingAction
它将扫描的程序集实际上取决于您在通话中提供的参数。
请注意,这实际上非常简单 - 最困难的部分是扫描正确的程序集并注册正确的类。你也可以手动完成,但这些扩展已经为你处理了。
请注意,即使反射得到了很大改善,这个过程相对较慢,所以尽量不要滥用它(例如,在测试中)。
最后,如果这些都不适合您,请记住您还需要设置AutoMapper以使用依赖注入解析器:
automapperConfiguration.ConstructServicesUsing(serviceProvider.GetService);