Autofac命名注册构造函数注入 [英] Autofac named registration constructor injection
问题描述
Autofac是否支持在组件的构造函数中指定注册名称?
Does Autofac support specifying the registration name in the components' constructors?
例如:Ninject的NamedAttribute
.
Example: Ninject's NamedAttribute
.
推荐答案
您需要使用顶部的Autofac.Extras.Attributed包来实现此目的
You need to use the Autofac.Extras.Attributed package on top to achieve this
因此,假设您有一个接口和两个类:
So let's say you have one interface and two classes:
public interface IHello
{
string SayHello();
}
public class EnglishHello : IHello
{
public string SayHello()
{
return "Hello";
}
}
public class FrenchHello : IHello
{
public string SayHello()
{
return "Bonjour";
}
}
然后您有一个消费者类,您要在其中选择要注入的实例:
Then you have a consumer class, which in you want to select which instance is injected:
public class HelloConsumer
{
private readonly IHello helloService;
public HelloConsumer([WithKey("EN")] IHello helloService)
{
if (helloService == null)
{
throw new ArgumentNullException("helloService");
}
this.helloService = helloService;
}
public string SayHello()
{
return this.helloService.SayHello();
}
}
注册和解决:
ContainerBuilder cb = new ContainerBuilder();
cb.RegisterType<EnglishHello>().Keyed<IHello>("EN");
cb.RegisterType<FrenchHello>().Keyed<IHello>("FR");
cb.RegisterType<HelloConsumer>().WithAttributeFilter();
var container = cb.Build();
var consumer = container.Resolve<HelloConsumer>();
Console.WriteLine(consumer.SayHello());
注册此类使用方时不要忘记AttributeFilter,否则解析将失败.
Do not forget the AttributeFilter when you register such a consumer, otherwise resolve will fail.
另一种方法是使用lambda代替属性.
Another way is to use a lambda instead of attribute.
cb.Register<HelloConsumer>(ctx => new HelloConsumer(ctx.ResolveKeyed<IHello>("EN")));
我找到了第二种选择,因为您也避免在项目中引用autofac程序集(只是导入属性),但这当然是个人观点.
I find the second option cleaner since you also avoid to reference autofac assemblies in your project (just to import an attribute), but that part is a personal opinion of course.
这篇关于Autofac命名注册构造函数注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!