wpf - 温莎城堡(或其他DI)-根据参数创建对象

标签 wpf mvvm dependency-injection inversion-of-control

对于整个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/

相关文章:

android - DataBinderMapperImpl 找不到 ActivityLoginBinding 的符号

java - 以 spring bean 作为属性的垃圾收集清理对象

.net - Windows WPF或Silverlight中的VT100终端仿真

wpf - 如何在 Helix Toolkit ViewPort 中设置不反光的 Material ?

WPF MVVM 将控件绑定(bind)到在 View 模型中设置的变量

c# - "FreshIOC.Container.Register"有什么作用?

dependency-injection - 使用 Guice Custom Scopes 和 Jersey 进行 Multi-Tenancy

angularjs - 如何使用 ES6 注入(inject) Angular 类

c# - Prism : Change the active view

c# - 更新经典桌面应用的 Application Insights 检测 key 的最佳实践