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)
完全按预期工作。
该建议的方法(见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)
| 归档时间: |
|
| 查看次数: |
1487 次 |
| 最近记录: |