[英]Find and validate all automapper mappings
I would like to be able to traverse an assembly for each type that is mapped as a source (or destination), and verify that the mapping configuration is valid. 我希望能够遍历映射为源(或目标)的每种类型的程序集,并验证映射配置是否有效。 This is for a rather large project that uses AutoMapper extensively and I'd like this unit test to break when a dev introduces an invalid mapping relationship. 这是一个广泛使用AutoMapper的相当大的项目,我希望这个单元测试在dev引入无效的映射关系时中断。 Looking at collection of GetAllMappedTypes, GetPropertyMaps, but I don't seem to be able to get to a way to check for a valid configuration. 查看GetAllMappedTypes,GetPropertyMaps的集合,但我似乎无法找到检查有效配置的方法。 We're using v4 of AutoMapper. 我们正在使用AutoMapper的v4。
The automapper code for this is: 这个的automapper代码是:
<Perform mapping configuration work>
Mapper.AssertConfigurationIsValid()
If you're using nunit, you can do: 如果你正在使用nunit,你可以这样做:
[TestFixture]
public class when_validating_mapping_config
{
[Test]
public void then_should_assert_mapping_configuration_is_valid()
{
// Arrange
MappingConfig.InitializeMappings(); // this is just however you initialize your mappings.
// Act
// Assert
Mapper.AssertConfigurationIsValid();
}
}
The mappingconfig is just how I initialize my mappings. mappingconfig就是我初始化映射的方式。 I am using automapper in MVC so all my static configuration happens in Global.asax.cs. 我在MVC中使用了automapper,所以我的所有静态配置都发生在Global.asax.cs中。
public static class MappingConfig
{
public static void InitializeMappings()
{
Mapper.Initialize(configuration => Configure(configuration));
}
public static void Configure(IConfiguration configuration)
{
configuration.CreateMap<Model, ViewModel>()
configuration.Seal();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.