c# - 初始化后将配置文件添加到自动映射器

标签 c# dependency-injection automapper

在某些外部程序集已经在 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/

相关文章:

c# - 如果我为集线器定义构造函数,连接将关闭

spring - @Autowired 有效但 @Inject 无效

c# - SQLDependency with DI

c# - 对象的 map 集合

c# - Automapper "IsNull"目标后缀无法正常工作

c# - 如何从 MySQL 数据库中选择数据以用于组合框选择?

c# - C# 的 C++ 代码帮助

c# - 如何在没有任何编码的情况下从串口读取二进制数据?

typescript - 如何借助 Automapper (TypeScript) 映射充满不同 DTO 的数组条目?

c# - 为 MSBuild 指定/未指定平台参数时的区别