c# – 使用Unity注入属性导致堆栈溢出

我已经使用Unity很长一段时间,但我一直使用它与构造函数注入.为了减少我必须注入到我的视图模型中的类的数量(因为我的命令依赖于它们),我想我会尝试创建一个使用Property Injection的概念,从而消除对大型构造函数参数列表的要求.这是场景……

我正在创建一个视图模型,其中的命令位于以某种方式使用/更新软件视图模型的属性上.我希望将View Model的实例传递给View Models属性上的Commands的构造函数.例如.

public Mainviewmodel
{
    public Mainviewmodel()
    {
        Customers = new ObservableCollection<Customerviewmodel>();
    }        

    [Depedency("LoadCommand")]
    public ICommand LoadCustomersCommand { get; set; }

    public ObservableCollection<Customerviewmodel> Customers { get; private set; }
}

public LoadCustomersCommand : ICommand
{
    public LoadCustomersCommand(Mainviewmodel mainviewmodel)
    {
        //Store view model for later use
    }

    //... implementation
}

//Setup code in App.Xaml

IUnityContainer unityContainer = new UnityContainer();
unityContainer.RegisterType<ICommand,LoadCommand>("LoadCommand");
unityContainer.RegisterType<Mainviewmodel>(new ContainerControlledLifetimeManager());

当我解析Mainviewmodel类时,我得到一个StackOverflow异常(如果Visual Studio完全回来的话).现在我希望Unity首先创建一个Mainviewmodel实例,因为它基本上是一个单例,然后查看View Model的实例并创建在新创建的Mainviewmodel中传递的Command,但显然我错了.

有任何想法吗?

解决方法

这是 Circular References错误,正如它所说,开发人员有责任避免它.所以Mainviewmodel引用了对Mainviewmodel的反馈的LoadCustomersCommand – >堆栈溢出.

所以你唯一能做的就是

public class Mainviewmodel
{
    public Mainviewmodel()
    {
        Customers = new ObservableCollection<Customerviewmodel>();
    }        

    //no dependency.
    public ICommand LoadCustomersCommand { get; set; }

    public ObservableCollection<Customerviewmodel> Customers { get; private set; }
}

解决你需要做以下事情

var mainModel = unityContainer.Resolve<Mainviewmodel>();
mainModel.LoadCustomersCommand =     unityContainer.Resolve<ICommand>("LoadCommand");

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么