繁体   English   中英

使用 Autofac 按属性解析不同的实例

[英]Resolve different instances by attribute with Autofac

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

我知道我们可以注册 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 class 的解析过程中,构造函数的参数“helloService”是 null。

是否可以使用 Autofac 实现这种行为,或者我错过了什么?

(与Autofac命名注册构造函数注入有关但不是同一个问题)

使用核心.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM