在autofac中为不同的构造函数配置两个相同类型的实例

问题描述 投票:0回答:1

我正在开发一个 ASP.NET 项目,使用 .NET 6、用于依赖项注入的 Autofac 和用于对象映射的 AutoMapper。在我的项目中,我有两个服务 A 和 B,每个服务都需要自己的 AutoMapper 配置。
我已经在我的

Startup.cs
中为服务 A 配置了 AutoMapper,使用以下代码:

var mappingConfigA = new MapperConfiguration(config =>
{
    config.AddProfile(new AMappingProfile());
});

IMapper mapperA = mappingConfigA.CreateMapper();

builder.RegisterInstance(mapperA).As<IMapper>().SingleInstance();

现在,我需要使用

IMapper
为服务 B 配置单独的
autofac.json
,同时保持服务 A 的配置不变。我想避免使用键过滤,而是使用
autofac.json
来定义服务 B 的
IMapper

我需要帮助了解如何使用

autofac.json
为服务 B 正确配置单独的 AutoMapper 配置文件,并确保它使用自己的映射器配置。任何见解或指导将不胜感激。

automapper .net-6.0 autofac
1个回答
0
投票

如果您想对单个接口使用两种实现方式,根据接线的具体情况,并且只想使用配置文件。您必须在配置文件中使用

key
属性并将控制器添加为服务。

我在https://github.com/soroshsabz/TestSolution

中添加了一些示例

但为了进一步解释,我在下面添加了这个示例

我的假设是

Controllers
,如下所示(使用
KeyFilter

public HomeController(ILogger<HomeController> logger,
                      [KeyFilter(nameof(DummyA))]IDummyModel dummyModel)
{
      _logger = logger;
      _dummyModel = dummyModel;
}

首先,我写了一个简单的

Startup.cs
来指定依赖加载的条件,并像下面这样写
ConfigureServices
ConfigureContainer

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().AddControllersAsServices();
        }

        public void ConfigureContainer(ContainerBuilder builder)
        {
            var configurationBuilder = new ConfigurationBuilder();
            configurationBuilder.AddJsonFile("autofac.json");
            var autoFacConfigurationModule = new ConfigurationModule(configurationBuilder.Build());

            builder.RegisterModule(autoFacConfigurationModule);

            //var controllers = typeof(Startup).Assembly.GetTypes().Where(t => t.BaseType == typeof(ControllerBase)).ToArray(); // for api controller
            var controllers = typeof(Startup).Assembly.GetTypes().Where(t => t.BaseType == typeof(Controller)).ToArray(); // for mvc controller
            builder.RegisterTypes(controllers).WithAttributeFiltering();
        }

然后我写一些如下的配置

{
  "components": [
    {
      "type": "AutofacHandyMVCTest.Models.DummyA, AutofacHandyMVCTest",
      "services": [
        {
          "type": "AutofacHandyMVCTest.Models.IDummyModel, AutofacHandyMVCTest",
          "key": "DummyA"
        }
      ],
      "instanceScope": "per-lifetime-scope"
    }
  ]
}

如你所见,如果我想加载

DummyA
我只需要在配置文件中将key设置为
DummyA
即可。

© www.soinside.com 2019 - 2024. All rights reserved.