在ASP.Net Core应用程序中的哪里验证AutoMapper配置?

Mr.*_*. T 8 automapper .net-core

正在构建ASP.Net Core 2.0 Web应用程序,无法确定在何处验证AutoMapper配置。

用我的ConfigureServices()方法,我有

services.AddAutoMapper();
Run Code Online (Sandbox Code Playgroud)

我正在自动映射器配置文件中注册我的映射

public class MyAutomapperProfile : Profile
{
    public MyAutomapperProfile()
    {
        CreateMap<FooDto, FooModel>();
        CreateMap<BarDto, BarModel>();
    }
}
Run Code Online (Sandbox Code Playgroud)

但不清楚在哪里打电话

Mapper.Configuration.AssertConfigurationIsValid();
Run Code Online (Sandbox Code Playgroud)

Mr.*_*. T 16

IMapper界面中进行挖掘(并感谢@LucianBargaoanu提供的文档链接)之后,我发现了我真正需要的东西。

ConfigureServices()

        // Adds AutoMapper to DI configuration and automagically scans the 
        // current assembly for any classes that inherit Profile 
        // and registers their configuration in AutoMapper
        services.AddAutoMapper();
Run Code Online (Sandbox Code Playgroud)

秘诀在于将其IMapper mapper作为参数添加到Configure()-参数列表依赖注入,因此您可以引用在中注册的任何服务ConfigureServices()

public void Configure(IApplicationBuilder app, ... , IMapper mapper)
{
  ...
        mapper.ConfigurationProvider.AssertConfigurationIsValid();
}
Run Code Online (Sandbox Code Playgroud)

完全按预期工作。

  • 如果有人查找它但在文档中没有找到它,则它似乎最近已被删除且没有任何解释。不过该解决方案仍然有效。https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection/commit/cfd27e2862fa0bfc5d737a261e9a124a141aa5fa#diff-04c6e90faac2675aa89e2176d2eec7d8 (2认同)
  • 这似乎是一个坏主意 - 配置由运行时调用来配置 HTTP 管道。您可以使用 if (env.IsDevelopment()) 包装 assertConfigurationIsValid 调用,但这仍然感觉是错误的方法。单元测试感觉更合适。 (2认同)

sar*_*rin 8

建议的方法(见JBogard的反应)是本次测试进入一个单元测试:

public class MappingTests
{
    private readonly IMapper _sut;

    public MappingTests() => _sut = new MapperConfiguration(cfg => { cfg.AddProfile<MyAutomapperProfile>(); }).CreateMapper();

    [Fact]
    public void All_mappings_should_be_setup_correctly() => _sut.ConfigurationProvider.AssertConfigurationIsValid();
}
Run Code Online (Sandbox Code Playgroud)