带参数的 AutoMapper 依赖注入

Mar*_*son 3 c# asp.net automapper asp.net-core

错误:AutoMapperConfiguration 没有无参数构造函数

我正在使用 nuget 包automapper DI

public class AutoMapperConfiguration : Profile
{
    private readonly ICloudStorage _cloudStorage;

    public AutoMapperConfiguration(ICloudStorage cloudStorage)
    {
        _cloudStorage = cloudStorage;

        // Do mapping here
    }
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<ICloudStorage, AzureStorage>();
    services.AddAutoMapper(); // Errors here
}
Run Code Online (Sandbox Code Playgroud)

如何使用带参数的自动映射器 DI?

Wil*_*Ray 5

我认为您无法将 DI 参数添加到Profiles. 这背后的部分逻辑可能是这些仅实例化一次,因此通过注册的服务AddTransient不会按预期运行。

一种选择是将其注入ITypeConverter:

public class AutoMapperConfiguration : Profile
{
    public AutoMapperConfiguration()
    {
        CreateMap<SourceModel, DestinationModel>().ConvertUsing<ExampleConverter>();
    }
}

public class ExampleConverter : ITypeConverter<SourceModel, DestinationModel>
{
    private readonly ICloudStorage _storage;

    public ExampleCoverter(ICloudStorage storage)
    {
        // injected here
        _storage = storage;

    }
    public DestinationModel Convert(SourceModel source, DestinationModel destination, ResolutionContext context)
    {
        // do conversion stuff
        return new DestinationModel();
    }
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<ICloudStorage, AzureStorage>();
    services.AddAutoMapper();
}
Run Code Online (Sandbox Code Playgroud)