在 ASP.NET Core 2.1 中使用 ConstructUsingServiceLocator() 时出现 AutoMapperMappingException

AutoMapperMappingException when using ConstructUsingServiceLocator() in ASP.NET Core 2.1

我在 ASP.NET Core 2.1 Web 应用程序中使用 AutoMapper 7.0.1 和 AutoMapper.Extensions.Microsoft.DependencyInjection 5.0.1。当我映射到未配置 ConstructUsingServiceLocator() 的类型时,映射有效。当我映射到配置为 ConstructUsingServiceLocator() 的类型时,它会抛出以下内容:

AutoMapperMappingException: Cannot create an instance of type 
AutoMapperTest.Destination
AutoMapper.MappingOperationOptions<TSource, TDestination>.CreateInstance<T>() in MappingOperationOptions.cs, line 47

我正在按照此处给出的 ASP.NET 核心使用 AutoMapper 的最新指南:

我在一个全新的项目中用一个最小的例子重现了这个。以下是相关部分:

新建项目 > APS.NET 核心 Web 应用程序 > Web 应用程序

安装 AutoMapper 7.0.1 和 AutoMapper.Extensions.Microsoft.DependencyInjection 5.0.1 Nuget 包。

来源:

public class Source
{
    public string Name { get; set; }
}

目的地:

public class Destination
{
    private readonly IDestinationRepository _repo;

    public Destination(IDestinationRepository repo)
    {
        _repo = repo ?? throw new ArgumentNullException(nameof(repo));
    }

    public string Name { get; set; }
}

IDestinationRepository:

public interface IDestinationRepository
{
}

目标存储库:

public class DestinationRepository : IDestinationRepository
{
}

映射配置文件:

public class MappingProfile : Profile
{
    public MappingProfile()
    {           
        CreateMap<Source, Destination>().ConstructUsingServiceLocator();
    }
}

Startup.ConfigureServices(IServiceCollection 服务):

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IDestinationRepository, DestinationRepository>();

    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.AddAutoMapper();
}

索引模型:

public class IndexModel : PageModel
{
    private readonly IMapper _mapper;

    public IndexModel(IMapper mapper)
    {
        _mapper = mapper;
    }

    public void OnGet()
    {
        _mapper.ConfigurationProvider.AssertConfigurationIsValid();            // <- Succeeds
        var repo = _mapper.ServiceCtor.Invoke(typeof(IDestinationRepository)); // <- repo is non-null

        var source = new Source {Name = "Test"};
        var destination = _mapper.Map<Source, Destination>(source);            // <- Fails!!
    }
}

上述 _mapper.Map<Source, Destination>(source) 调用失败,但出现上面列出的异常。我已验证 MappingProfile 正在加载。

如果我将 Destination ctor 更改为无参数,它仍然会失败。

但是,如果我从 MappingProfile 中删除 ConstructUsingServiceLocator()(使用空的 Destination ctor),我的映射就会开始工作。

我在这里做错了什么?感谢您的帮助!

您的 Destination class 未在 di 容器中注册,因此无法让 di 容器创建 class Destination.[=12 的新实例=]