Autofac是否支持在组件的构造函数中指定注册名称?
示例:Ninject 的NamedAttribute
.
您需要使用顶部的 Autofac.Extras.Attributed 包来实现此目的
假设您有一个接口和两个类:
public interface IHello
{
string SayHello();
}
public class EnglishHello : IHello
{
public string SayHello()
{
return "Hello";
}
}
public class FrenchHello : IHello
{
public string SayHello()
{
return "Bonjour";
}
}
然后你有一个消费者类,你想在其中选择注入哪个实例:
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,否则解析会失败。
另一种方法是使用 lambda 代替属性。
cb.Register<HelloConsumer>(ctx => new HelloConsumer(ctx.ResolveKeyed<IHello>("EN")));
我发现第二个选项更干净,因为您还避免在项目中引用 autofac 程序集(只是为了导入属性),但这部分当然是个人意见。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)