gpt4 book ai didi

structuremap - Autofac vs. Structuremap,如何注入(inject)接口(interface)的所有实例?

转载 作者:行者123 更新时间:2023-12-04 04:20:37 31 4
gpt4 key购买 nike

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

来自 autofac 的文档:here

For example, when Autofac is injecting a constructor parameter of type IEnumerable it will not look for a component that supplies IEnumerable. Instead, the container will find all implementations of ITask and inject all of them.



StructureMap 中是否提供此功能?

对于我的类(class):
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 中,您可以执行以下操作:

ObjectFactory.Intialize(x => x.Scan(y => y.AddAllTypesOf<IFoo>()));
这将注册所有类型的 IFoo那么当你解析 UsingFoo ,它们将被注入(inject)。
编辑:
我只是在控制台应用程序中快速写了这个:
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();
}
}
输出是:

This is from Foo 1

This is from Foo 2

Done

关于structuremap - Autofac vs. Structuremap,如何注入(inject)接口(interface)的所有实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9832425/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com