在构造函数中使用Mapper.Initialize

时间:2015-07-26 05:05:20

标签: c# automapper

我正在使用AutoMapper将我的POCO映射到DTO。 对于Unit可测试性,我将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是否会尝试在下一个对象创建时从头开始构建所有映射,或者它是否足够聪明以至于不能再次映射相同的对象?

1 个答案:

答案 0 :(得分:2)

每个AppDomain只应调用一次Mapper.Initialize,如果你不只是在应用程序启动时调用它(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);
    }
}