AutoMapper 与 DI:无法创建类型的实例...使用 ValueResolver 时

EM1*_*M15 1 c# automapper .net-core

我有一个.NET Core 3.1 API 和以下 Nuget 包:

  • 自动映射器(10.1.1)
  • AutoMapper.Extensions.Microsoft.DependencyInjection (8.1.1)

我正在尝试使用ValueResolver将值从实体映射到 dto,但出现异常:

AutoMapperMappingException:无法创建 TestAutomapperResolver.Mapping.CustomResolver 类型的实例

启动.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddAutoMapper(cfg => cfg.AddMaps(typeof(TestProfile).Assembly));
}
Run Code Online (Sandbox Code Playgroud)

测试配置文件.cs

public class TestProfile : Profile
{
    public TestProfile()
    {
        CreateMap<TestEntity, TestDto>()
            .ForMember(src => src.PropertyToBeMappedByResolver, opts => opts.MapFrom<CustomResolver>());
    }
}

public class CustomResolver : IValueResolver<TestEntity, TestDto, string>
{
    public string Resolve(TestEntity source, TestDto destination, string destMember, ResolutionContext context)
    {
        return "String generated with resolver";
    }
}
Run Code Online (Sandbox Code Playgroud)

当我这样做时,mapper.CreateMap<TestDto>(entity);我收到了这个异常。

顺便说一句,使用此解析器作为opts => opts.MapFrom(CustomResolver())不是一个选项,因为我想将一些服务注入到该解析器中。

任何想法?

Ada*_*one 8

AddMaps你在不该使用的时候使用了。AddMaps仅添加配置文件和映射,但不添加 DI 包所做的所有额外服务。

这将正确地做到这一点:

services.AddAutoMapper(typeof(TestProfile).Assembly);
Run Code Online (Sandbox Code Playgroud)

现在,AutoMapper 在这里给你一个非常无益的错误,但问题可以追溯到 Microsoft 依赖注入。DI 不知道您的自定义解析器类型,因此它甚至不会尝试。

由于您没有使用 DI 包的扩展方法,因此解析器不会添加到服务集合中。如果需要,您可以手动添加这些服务:

services.AddAutoMapper(cfg => cfg.AddMaps(typeof(TestProfile).Assembly));
services.AddTransient<CustomResolver>();
Run Code Online (Sandbox Code Playgroud)