简体   繁体   English

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

[英]Where to validate AutoMapper Configuration in ASP.Net Core application?

Building an ASP.Net Core 2.0 web application and can't figure out where to validate the AutoMapper configuration.构建 ASP.Net Core 2.0 Web 应用程序,但不知道在哪里验证 AutoMapper 配置。

In my ConfigureServices() method, I have在我的ConfigureServices()方法中,我有

services.AddAutoMapper();

And I'm registering my mappings in an Automapper Profile我正在 Automapper Profile 中注册我的映射

public class MyAutomapperProfile : Profile
{
    public MyAutomapperProfile()
    {
        CreateMap<FooDto, FooModel>();
        CreateMap<BarDto, BarModel>();
    }
}

But it's not clear where to call但不清楚在哪里打电话

Mapper.Configuration.AssertConfigurationIsValid();

After digging around in the IMapper interface (and thanks to the documentation link provided by @LucianBargaoanu), I found exactly what I needed.IMapper界面中挖掘之后(感谢@LucianBargaoanu 提供的文档链接),我找到了我所需要的。

In ConfigureServices() :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();

The secret sauce is to add IMapper mapper as a parameter to Configure() - the parameter list is dependency-injected so you can reference any service registered in ConfigureServices()秘诀是将IMapper mapper作为参数添加到Configure() - 参数列表是依赖注入的,因此您可以引用在ConfigureServices()注册的任何服务

public void Configure(IApplicationBuilder app, ... , IMapper mapper)
{
  ...
        mapper.ConfigurationProvider.AssertConfigurationIsValid();
}

Works exactly as expected.完全按预期工作。

The recommended approach (see JBogard's response) is to move this test into a unit test: 推荐的方法(请参阅 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM