Asp.net core 2.0 AutoMapper IValueResolver dependency injection

时间:2018-03-22 23:53:09

标签: dependency-injection automapper asp.net-core-2.0 resolver

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

1 个答案:

答案 0 :(得分:0)

Lucian的建议是正确的 - AutoMapper.Extensions.Microsoft.DependencyInjection包是要走的路。即使你不想使用它,你也必须做类似的事情。

我遇到了同样的问题,通过使用扩展,您只需修改注册AutoMapper及其配置的入口点。

扩展程序的作用是什么(source):

  1. 使用提供的配置初始化Automapper
  2. 它会扫描您可以通过依赖注入实现的所有类,并将它们注册为瞬态,查找以下实现:

    • IValueResolver
    • IMemberValueResolver
    • ITypeConverter
    • IMappingAction

    它将扫描的程序集实际上取决于您在通话中提供的参数。

  3. 如果其中任何一个都可以实际实例化,那么它们将被注册为瞬态实现。
  4. 就这样,AutoMapper会向服务提供商请求这些实例,这将解决它们,为此,它还将解决任何未决的依赖关系。
  5. 请注意,这实际上非常简单 - 最困难的部分是扫描正确的程序集并注册正确的类。你也可以手动完成,但这些扩展已经为你处理了。

    请注意,即使反射得到了很大改善,这个过程相对较慢,所以尽量不要滥用它(例如,在测试中)。

    最后,如果这些都不适合您,请记住您还需要设置AutoMapper以使用依赖注入解析器:

    automapperConfiguration.ConstructServicesUsing(serviceProvider.GetService);