gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:56:16 27 4
gpt4 key购买 nike

我正在使用 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);
}
}

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com