【问题标题】:Autofac vs. Structuremap, how do I inject all instances of an interface?Autofac vs. Structuremap,如何注入接口的所有实例?
【发布时间】:2012-03-23 00:14:00
【问题描述】:

在 autoFac 中,我可以注册一个接口的多个实现。当 autofac 实例化我的对象时,所有实例都会传递给构造函数。

来自 autofac 的文档:here

例如,当 Autofac 注入类型为的构造函数参数时 IEnumerable 它不会寻找提供的组件 可数的。相反,容器会找到所有 ITask 的实现并将它们全部注入。

StructureMap 中是否提供此功能?

对于我的课程:

public interface IFoo
{

}

public class Foo1 : IFoo
{

}

public class Foo2 : IFoo
{

}

public class UsingFoo
{
    public UsingFoo(IEnumerable<IFoo> allFoos)
    {
        foreach (var foo in allFoos)
        {

        }
    }
}

如何注册我的实现,以便在实例化 UsingFoo 时,将向构造函数传递 IFoo 的所有实现?

【问题讨论】:

    标签: structuremap autofac


    【解决方案1】:

    在 StructureMap 中你可以这样做:

    ObjectFactory.Intialize(x => x.Scan(y => y.AddAllTypesOf<IFoo>()));
    

    这将注册所有类型的IFoo

    那么当你解析UsingFoo时,它们就会被注入。

    编辑:

    我只是在控制台应用程序中快速写了这个:

    ObjectFactory.Initialize(x =>
    {
        x.Scan(y =>
        {
            y.AddAllTypesOf<IFoo>();
        });
    });
    
    var usingFoo = ObjectFactory.GetInstance<UsingFoo>();
    

    编辑:

    你让我怀疑自己,所以我仔细检查了。

    效果很好。

    这是我在控制台应用程序中快速编写的一个工作示例:

    public interface IFoo
    {
        string Text { get; }
    }
    
    public class Foo1 : IFoo
    {
        public string Text
        {
            get { return "This is from Foo 1"; }
        }
    }
    
    public class Foo2 : IFoo
    {
        public string Text
        {
            get { return "This is from Foo 2"; }
        }
    }
    
    public class Bar
    {
        private readonly IEnumerable<IFoo> _myFoos;
    
        public Bar(IEnumerable<IFoo> myFoos)
        {
            _myFoos = myFoos;
        }
    
        public void Execute()
        {
            foreach (var myFoo in _myFoos)
            {
                Console.WriteLine(myFoo.Text);
            }
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            ObjectFactory.Initialize(x =>
            {
                x.UseDefaultStructureMapConfigFile = false;
                x.Scan(y =>
                {
                    y.TheCallingAssembly();
                    y.AddAllTypesOf<IFoo>();
                });
            });
    
            var myBar = ObjectFactory.GetInstance<Bar>();
    
            myBar.Execute();
    
            Console.WriteLine("Done");
            Console.ReadKey();
        }
    }
    

    输出是:

    这是来自 Foo 1

    这是来自 Foo 2

    完成

    【讨论】:

    • 我不认为你是对的。这只会注入一个 IFoo 实例。我需要 SM 将 IFoo 的所有实例作为 IEnumerable. 注入
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多