[英]How do you setup an ASP.Net 3.0 Core Web API project to use AutoFac and NLog?
[英]How do you resolve a specific keyed service in ASP.NET Core when using Autofac?
我在简单的 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");
我知道一个事实,我可以注册我的类型要么使用这些绑定的,我知道有一种方法可以得到适当的类型,讨论在这里:
var services = serviceProvider.GetServices<ITestService>();
var testComponent= services.First(o => o.GetType() == typeof(TestComponent));
由于我使用 Autofac 并使用 Keyed Services 注册我的类型,我如何使用 IServiceProvider 和我在绑定中提供的密钥(“服务”或“组件”)解析正确的 ITestService ?
根据文档,有两种更干净的方法来解析键控服务。 您可以使用索引解决:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.