【问题标题】:How do you resolve a specific keyed service in ASP.NET Core when using Autofac?使用 Autofac 时如何解析 ASP.NET Core 中的特定键控服务?
【发布时间】:2018-08-20 00:51:51
【问题描述】:

我在简单的 ASP.NET Core Web API 中创建,假设我有一个如下界面:

public interface ITestService
{
    string GetDate();
}

我正在使用 Autofac 处理 DI,对于上述接口我有两个注册类型(TestService 和 TestComponent 实现 ITestService):

builder.RegisterType<TestService>().As<ITestService>().Keyed<ITestService>("service");
builder.RegisterType<TestComponent>().As<ITestService>().Keyed<ITestService>("component");

我知道我可以注册我的类型以使用这些绑定中的任何一个,并且我知道有一种方法可以获得正确的类型,如 here 所述:

var services = serviceProvider.GetServices<ITestService>();
var testComponent= services.First(o => o.GetType() == typeof(TestComponent));

由于我使用 Autofac 并使用 Keyed Services 注册了我的类型,如何使用 IServiceProvider 和我在绑定中提供的密钥(“服务”或“组件”)解析正确的 ITestService?

【问题讨论】:

    标签: c# asp.net-core asp.net-core-mvc autofac


    【解决方案1】:

    根据documentation,还有两种更干净的方法可以解决密钥服务。您可以使用索引来解决:

    public class TestServiceConsumer
    {
        private ITestService testService;    
    
        public TestServiceConsumer(IIndex<string, ITestService> testServices)
        {
            testService = testServices["service"];
        }
    }
    

    它也可以用 Attribute 来完成(它似乎更适合你的情况):

    public class TestServiceConsumer
    {
        private ITestService testService;    
    
        public TestServiceConsumer([KeyFilter("service")] ITestService testService)
        {
            this.testService = testService;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-27
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 2022-01-08
      • 1970-01-01
      • 2018-08-31
      • 2019-08-24
      • 1970-01-01
      相关资源
      最近更新 更多