在某些外部程序集已经在 DI 设置上添加了映射器配置后,添加配置文件时遇到一些问题。
首先我只是添加了一些代码来添加配置文件
var mapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.AddProfile<DataMappingProfile>();
});
mapperConfiguration.AssertConfigurationIsValid();
services.AddSingleton<IMapper>(new Mapper(mapperConfiguration));
但后来我覆盖了一些其他的映射配置文件。
所以我在想,我应该尝试将我的添加到现有的映射配置中。
我是这样走的
var sp = services.BuildServiceProvider();
var autoMapper = sp.GetService<IMapper>();
var mapperConfiguration = autoMapper?.ConfigurationProvider as MapperConfiguration;
var configuration = new MapperConfigurationExpression();
configuration.AddProfile<LpisMappingProfile>();
if (mapperConfiguration == null)
{
mapperConfiguration = new MapperConfiguration(configuration);
}
else
{
//add the previous as well
//?? add this `configuration` ?
}
mapperConfiguration.AssertConfigurationIsValid();
services.AddSingleton<IMapper>(new Mapper(mapperConfiguration));
但我有点卡在 else
流程上。
有什么建议吗?
谢谢!
最佳答案
那是不可能的。如果程序集使用私有(private) MapperConfiguration,那是它自己的事。如果它想与应用程序协作,它不应该定义一个 MapperConfiguration,它应该定义应用程序扫描的配置文件并添加到应用程序拥有的单例 MapperConfiguration。 AM 配置是只读的,在初始化阶段之后无法更改它。
关于c# - 初始化后将配置文件添加到自动映射器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51283992/