对于整个DI/IoC事情,我还是一个新手,所以请忍受...
我有这种设置:
interface IA
interface IB
interface IC
abstract class A : IA
class B : A, IB
class C : A, IC
interface IX
interface IY
interface IZ
abstract class X : IX
class Y : X, IY
class Z : X, IZ
B和C的构造函数如下所示:
public B(IY y);
public C(IZ z);
现在,我希望基于已经创建的Y或Z实例构造B或C。
像这样:
IX x = new ...; // either Y or Z, determined at runtime
// lots of code
IA a = fancyfuncoftruth<IA>(x); // creates an instance of either B or C, depending on x
这样的事情可能吗?
为您提供一些背景知识:我正在尝试将WPF的树 View ,MVVM模式和DI结合起来。
谢谢你的时间。
最佳答案
我不确定我是否了解您要查找的内容,但是在我看来,您是在询问是否存在可以根据特定的IX(x)值正确解析IA的功能。
您最好使用将IX实例映射到IA的Abstract Factory来实现。
我个人将其实现为自定义的Abstract Factory,但您也可以使用CaSTLe Windsor的UsingFactory或UsingFactoryMethod:
IX x = new ...;
var container = new WindsorContainer();
container.AddFacility<FactorySupportFacility>();
container.Register(Component.For<IA>().UsingFactoryMethod(k =>
{
// Do fancy stuff with x here
// This example just shows that x can be referenced
// in the closure, but I'm not using it...
if (x == null)
{
}
return k.Resolve<B>();
}));
container.Register(Component.For<B>());
container.Register(Component.For<IY>().ImplementedBy<Y>());
var result = container.Resolve<IA>();
关于wpf - 温莎城堡(或其他DI)-根据参数创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1522527/