我正在将我的 AutoMappers 从使用一个大型 AutoMapperConfiguration 类转换为使用实际配置文件。全局现在看起来像这样(暂时原谅 Open/Close 违规)
Mapper.Initialize(x =>
{
x.AddProfile<ABCMappingProfile>();
x.AddProfile<XYZMappingProfile>();
// etc., etc.
});
让我脱颖而出的关键部分和以前一直阻止我使用配置文件的障碍是我的 ninject 绑定(bind)。我永远无法让绑定(bind)工作。
之前我有这个绑定(bind):
Bind<IMappingEngine>().ToConstant(Mapper.Engine).InSingletonScope();
我已经迁移到这个绑定(bind):
Bind<IMappingEngine>().ToMethod(context => Mapper.Engine);
现在可以了,该应用程序正常运行,我有个人资料,一切都很好。
障碍现在在我的单元测试中。使用 NUnit,我将设置我的构造函数依赖项。
private readonly IMappingEngine _mappingEngine = Mapper.Engine;
然后在我的 [Setup] 方法中,我将构建我的 MVC Controller 并调用 AutoMapperConfiguration 类。
[SetUp]
public void Setup()
{
_apiController = new ApiController(_mappingEngine);
AutoMapperConfiguration.Configure();
}
我现在已经修改为。
[SetUp]
public void Setup()
{
_apiController = new ApiController(_mappingEngine);
Mapper.Initialize(x =>
{
x.AddProfile<ABCMappingProfile>();
x.AddProfile<XYZMappingProfile>();
// etc., etc.
});
}
不幸的是,这似乎不起作用。当我点击使用映射的方法时,映射似乎没有被拾取,AutoMapper 抛出异常,说明映射不存在。关于如何/如何更改测试中的映射器定义/注入(inject)以解决此问题的任何建议?我猜 IMappingEngine 字段的定义是我的问题,但不确定我有什么选择。
谢谢
最佳答案
您遇到的问题是使用静态 Mapper.Engine
的结果这是某种包含 AutoMapper 配置的单例。按照惯例,Mapper.Engine
配置后不应更改。因此,如果您想通过提供 AutoMapper.Profiler
来配置 Automapper对于每个单元测试,您应该避免使用它。
更改非常简单:将您的类添加到实例 AutoMapperConfiguration
它自己的实例AutoMapper.MappingEngine
而不是使用全局静态 Mapper.Engine
.
public class AutoMapperConfiguration
{
private volatile bool _isMappinginitialized;
// now AutoMapperConfiguration contains its own engine instance
private MappingEngine _mappingEngine;
private void Configure()
{
var configStore = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers());
configStore.AddProfile(new ABCMappingProfile());
configStore.AddProfile(new XYZMappingProfile());
_mappingEngine = new MappingEngine(configStore);
_isMappinginitialized = true;
}
/* other methods */
}
ps:full sample is here
关于.net - AutoMapper 配置文件和单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16153592/