c# – 使用Unity注入属性导致堆栈溢出
发布时间:2020-12-15 08:31:15  所属栏目:百科  来源:网络整理 
            导读:我已经使用Unity很长一段时间,但我一直使用它与构造函数注入.为了减少我必须注入到我的视图模型中的类的数量(因为我的命令依赖于它们),我想我会尝试创建一个使用Property Injection的概念,从而消除对大型构造函数参数列表的要求.这是场景…… 我正在创建一个
                
                
                
            | 
                         我已经使用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");
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
