我正在使用 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/