【问题标题】:Resolve different instances by attribute with Autofac使用 Autofac 按属性解析不同的实例
【发布时间】:2019-09-20 08:44:09
【问题描述】:

我想知道是否可以使用 Autofac 注册同一类的不同实例,然后在消费者类的构造函数中使用属性解析正确的实例。

我知道我们可以注册 2 种不同的接口实现,并使用属性解析好的实现。例如:

 ContainerBuilder cb = new ContainerBuilder();

 cb.RegisterType<EnglishHello>().Keyed<IHello>("EN");
 cb.RegisterType<FrenchHello>().Keyed<IHello>("FR");
 cb.RegisterType<HelloConsumer>().WithAttributeFilter();
 var container = cb.Build();

并且依赖项将像这样使用:

   public class HelloConsumer  { 
         public HelloConsumer([KeyFilter("EN")] IHello helloService)
         {  } 
    }

第一个示例一切正常。

我尝试了以下方法:

var helloEn=new Hello();
var helloFr=new Hello();    
//init properties...
helloFr.Greetings="Salut";
helloEn.Greetings="Hi";

cb.Register<Hello>(x=>helloEn).Keyed<IHello>("EN");
cb.Register<Hello>(x=>helloFr).Keyed<IHello>("FR");

编译正常,但是在解析HelloConsumer类的过程中,构造函数的参数“helloService”为空。

是否有可能使用 Autofac 实现这种行为,还是我错过了什么?

(与Autofac named registration constructor injection相关但不是同一个问题)

【问题讨论】:

    标签: c# .net-core autofac


    【解决方案1】:

    带有核心.WithAttributeFiltering() 扩展。这似乎工作得很好。

    using System;
    using Autofac;
    using Autofac.Features.AttributeFilters;
    
    public class Program
    {
        public interface IHello
        {
             string Greetings { get; }
        }
    
        public class Hello : IHello
        {
            public string Greetings
            {
                get;
                set;
            }
        }
    
        public class HelloConsumer
        {
            public HelloConsumer([KeyFilter("EN")] IHello hello)
            {
                Console.WriteLine(hello.Greetings);
            }
        }
    
        public static void Main()
        {
            ContainerBuilder cb = new ContainerBuilder();
            cb.RegisterType<HelloConsumer>().AsSelf().WithAttributeFiltering();
            var helloEn = new Hello { Greetings = "Hi" };
            var helloFr = new Hello { Greetings = "Bonjour" };
            cb.Register<Hello>(x => helloEn).Keyed<IHello>("EN");
            cb.Register<Hello>(x => helloFr).Keyed<IHello>("FR");
            var container = cb.Build();
    
            container.Resolve<HelloConsumer>(); // Should write the correct greeting
        }
    }
    

    小提琴:https://dotnetfiddle.net/3s6oFc

    【讨论】:

    • 谢谢。你是对的,它有效。我意识到我在示例中过度简化了问题。我认为真正的问题是我对“Register”的调用是异步完成的,并且发生在对“container.Build”的调用之后。如果是这种情况,我会尽快检查,更新我的帖子,并接受您的回答。
    猜你喜欢
    • 2015-05-11
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2018-01-13
    相关资源
    最近更新 更多