WPF ViewModel中的Castle Windsor构造函数注入

3

我正在尝试避免使用Container.Resolve()反模式。如何更改以下内容以使用构造函数注入?

Installers.cs

 public void Install(Castle.Windsor.IWindsorContainer container, 
                            Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
        {

            container.AddFacility<TypedFactoryFacility>();

            container

             .Register(Component.For<IData>()
                .ImplementedBy<Data>().LifeStyle.Singleton)



        }

BootStrapper.cs

public class Bootstrapper
    {
        private static volatile IWindsorContainer _theWindsorContainer;
        private static object syncRoot = new Object();

        public static IWindsorContainer Container
        {
            get
            {
                if (_theWindsorContainer == null)
                {
                    lock (syncRoot)
                    {
                        if (_theWindsorContainer == null)
                        {
                            _theWindsorContainer = new WindsorContainer().Install(FromAssembly.This());
                        }
                    }
                }

                return _theWindsorContainer;
            }
        }
    }

OViewModel.cs

public IData ThisData {get;set;}

public OViewModel()
{

  ThisData= Bootstrapper.Container.Resolve<IData>(); 
  InitializeComponent(); 
}

如何使用Windsor Castle构造函数注入来初始化ViewModel并进行构造函数注入?无论是InitializeComponent没有被调用还是ThisData为空,都能实现。
2个回答

4

我几年前写了一篇文章,关于如何将Castle Windsor集成到WPF中,在视图模型中实现依赖注入。这可能是你正在寻找的。


0

我不熟悉Castle Windsor的细节,但通常你会像这样构建你的OViewModel:

public class OViewModel
{
  public IData ThisData { get; set; } //private set??

  public OViewModel(IData _thisData)
  {
    ThisData = _thisData;
    InitializeComponent();
  }
}

这将是构造函数注入。您可以搜索参数注入术语以了解其他完成方式。

但基本上,当容器解析OViewModel时,它知道如何解析IData,并会自动为您解析它。

当然,这只是备份 - 创建OViewModel的任何内容都需要使用container.Resolve,而您不希望这样做。因此,您可能会将视图模型(或其接口)(或工厂对象)注入到该父对象中。一直回溯到您需要从容器中解析以启动所有内容的单个对象,这是应用程序根源。

希望对Castle Windsor的细节有更多了解的人可以给您提供更多详细信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接