c# - 在构造函数中使用 Mapper.Initialize

标签 c# automapper

我正在使用 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 是否会在下一个对象创建时尝试从头开始构建所有映射,或者它是否足够智能,不会再次映射相同的对象?

最佳答案

每个 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);
    }
}

关于c# - 在构造函数中使用 Mapper.Initialize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31633826/

相关文章:

c# - 如何在 Automapper 中映射嵌套的子对象属性

asp.net - 使用嵌套对象在 Linq 中将 IQueryable<Entity> 映射到 IQueryable<DTO>

c# - AutoMapper Project().To<T> 和可重用的 lambda 表达式

c# - ASP.NET Identity 在每次请求时重新生成 Identity

c# - Windows Task Scheduler Daily Trigger 运行持续时间

asp.net-mvc - 在哪里放置验证注释 ViewModel 或 Domain 对象?

c# - AutoMapper - 将派生类映射到 Dto

c# - 在碰撞解决方法中应用恢复系数

c# - Windows 上的视频叠加(使用 C#?)

c# - 关于数据结构设计的问题