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

标签 c# asp.net-core automapper 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

我正在遵循此处给出的将 AutoMapper 与 ASP.NET Core 结合使用的最新指南:How to pass a service from .net core di container to a new object created with automapper

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

新建项目 > APS.NET Core 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 是无参数的,它仍然失败。

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

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

最佳答案

您的 Destination 类未在 di 容器中注册,因此无法让 di 容器创建类 Destination 的新实例。

关于c# - 在 ASP.NET Core 2.1 中使用 ConstructUsingServiceLocator() 时出现 AutoMapperMappingException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51965677/

相关文章:

c# - 每个程序集调用一次 AddAutoMapper 而不是传入多个程序集?

c# - 我可以在 lock 语句中使用 Interlocked.Increment 吗?

c# - 使用 C# 在 SQL Server 中存储图像

c# - 用 List<derivedClass> 覆盖 List<baseClass>

c# - 生成的 AAD CallbackUrl 是 IP 地址,与部署到服务结构时应用程序注册中的回复 Url 不匹配

c# - OpenIdConnectAuthenticationHandler : message. 状态为 null 或为空

c# - 如何在 C# 中使 Dropdownlist 只读

visual-studio - 出现一个或多个错误,无法启动调试适配器 Visual Studio 2019

c# - 强类型通用属性替代方案

entity-framework - automapper 是否可以防止使用 EF 进行延迟加载?