在构造函数中使用 Mapper.Initialize

Using Mapper.Initialize in constructor

我正在使用 AutoMapper 将我的 POCO 映射到 DTO。 对于单元可测试性,我将 IMapping 引擎传递到我的构造函数中,并在构造函数为 null 的情况下使用 Mapper.Initialize。

public class PeopleEfProvider : IPeopleDbContext
{
    public IMappingEngine MappingEngine { get; set; }
    public DatabaseHelpersRepo DatabaseHelpersRepo { get; set; }
    public PeopleDataContext DataContext { get; set; }
    public PeopleEfProvider(PeopleDataContext dataContext = null, IMappingEngine mappingEngine = null)
    {
        DataContext = dataContext ?? new PeopleDataContext();
        // if mappingEngine is coming from Unit Test or from another Client then use it.
        if (mappingEngine == null)
        {               
            Mapper.Initialize(mapperConfiguration =>
            {
                mapperConfiguration.AddProfile(new PeopleEfEntityProfile());
            });
            Mapper.AssertConfigurationIsValid();
            MappingEngine = Mapper.Engine;
        }
        else
        {
            MappingEngine = mappingEngine;
        }
        DatabaseHelpersRepo = new DatabaseHelpersRepo(DataContext, MappingEngine);
    }
}

以这种方式使用 AutoMapper 有什么缺点吗?我 运行 我的集成测试超过 1000 循环并没有发现任何问题,另一方面我不能说当我把它放在网上时是否可行。

AutoMapper 会尝试在下一个对象创建时从头开始构建所有映射,还是它足够聪明,不会再次映射相同的对象?

Mapper.Initialize 每个 AppDomain 应该只调用一次,如果你不只是在应用程序启动时调用它(App_Start 等),你会遇到一些不稳定的线程问题。

您也可以创建惰性初始化器来完成同样的事情:

public class PeopleEfProvider : IPeopleDbContext
{
    private static Lazy<IMappingEngine> MappingEngineInit = new Lazy<IMappingEngine>(() => {
        Mapper.Initialize(mapperConfiguration =>
        {
            mapperConfiguration.AddProfile(new PeopleEfEntityProfile());
        });
        Mapper.AssertConfigurationIsValid();
        return Mapper.Engine;
    });
    public IMappingEngine MappingEngine { get; set; }
    public DatabaseHelpersRepo DatabaseHelpersRepo { get; set; }
    public PeopleDataContext DataContext { get; set; }
    public PeopleEfProvider(PeopleDataContext dataContext = null, IMappingEngine mappingEngine = null)
    {
        DataContext = dataContext ?? new PeopleDataContext();
        MappingEngine = mappingEngine ?? MappingEngineInit.Value;
        DatabaseHelpersRepo = new DatabaseHelpersRepo(DataContext, MappingEngine);
    }
}