AutoMapper配置文件和单元测试

Khe*_*pri 8 .net asp.net-mvc nunit ninject automapper

我正在使用一个大型AutoMapperConfiguration类来使用实际的配置文件.全球现在看起来像是这样(暂时原谅Open/Close违规)

Mapper.Initialize(x =>
                       {
                          x.AddProfile<ABCMappingProfile>();
                          x.AddProfile<XYZMappingProfile>();
                          // etc., etc.
                  });
Run Code Online (Sandbox Code Playgroud)

让我超越顶部的关键部分和以前总是阻止我使用配置文件的障碍是我的ninject绑定.我永远无法使绑定工作.之前我有这个绑定:

Bind<IMappingEngine>().ToConstant(Mapper.Engine).InSingletonScope();
Run Code Online (Sandbox Code Playgroud)

我已经迁移到这个绑定:

Bind<IMappingEngine>().ToMethod(context => Mapper.Engine);
Run Code Online (Sandbox Code Playgroud)

这现在有效,应用程序功能齐全,我有个人资料,事情很好.

这个故障现在在我的单元测试中.使用NUnit,我将设置我的构造函数依赖项.

private readonly IMappingEngine _mappingEngine = Mapper.Engine;
Run Code Online (Sandbox Code Playgroud)

然后在我的[Setup]方法中构建我的MVC控制器并调用AutoMapperConfiguration类.

[SetUp]
public void Setup()
{
    _apiController = new ApiController(_mappingEngine);
    AutoMapperConfiguration.Configure();
}
Run Code Online (Sandbox Code Playgroud)

我现在修改为.

[SetUp]
public void Setup()
{
    _apiController = new ApiController(_mappingEngine);

    Mapper.Initialize(x =>
                          {
                              x.AddProfile<ABCMappingProfile>();
                              x.AddProfile<XYZMappingProfile>();
                              // etc., etc.
                          });
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这似乎不起作用.当我点击使用映射的方法时,映射似乎没有被拾取,AutoMapper抛出一个异常,说明映射不存在.有关如何/如何更改测试中的映射器定义/注入以解决此问题的任何建议?我猜测IMappingEngine字段的定义是我的问题,但不确定我有什么选择.

谢谢

Aki*_*kim 3

您遇到的问题是使用 static 的结果Mapper.Engine,它是某种包含 AutoMapper 配置的单例。按照惯例,Mapper.Engine配置后不应更改。因此,如果您想通过提供AutoMapper.Profiler每个单元测试来配置 Automapper,则应避免使用它。

更改非常简单:将其AutoMapperConfiguration自己的实例添加到类的实例中AutoMapper.MappingEngine,而不是使用全局 static 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 */
}
Run Code Online (Sandbox Code Playgroud)

ps:完整样本在这里