C# Unity属性注入导致堆栈溢出

C# Unity属性注入导致堆栈溢出,c#,mvvm,dependency-injection,unity-container,C#,Mvvm,Dependency Injection,Unity Container,我已经使用Unity很长一段时间了,但我总是在构造函数注入中使用它。为了减少必须注入视图模型的类的数量(因为我的命令依赖于它们),我想尝试创建一个使用属性注入的概念,从而取消对大型构造函数参数列表的要求。下面是一个场景 我正在创建一个视图模型,其中的命令位于以某种方式使用/更新软管视图模型的特性上。我希望将视图模型的实例传递给位于视图模型属性上的命令的构造函数。例如 public MainViewModel { public MainViewModel() { C

我已经使用Unity很长一段时间了,但我总是在构造函数注入中使用它。为了减少必须注入视图模型的类的数量(因为我的命令依赖于它们),我想尝试创建一个使用属性注入的概念,从而取消对大型构造函数参数列表的要求。下面是一个场景

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

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());
public主视图模型
{
公共主视图模型()
{
客户=新的可观察收集();
}        
[依赖性(“加载命令”)]
公共ICommand LoaderCustomerCommand{get;set;}
公共可观测集合客户{get;private set;}
}
公共加载程序CustomerCommand:ICommand
{
公共加载自定义命令(MainViewModel MainViewModel)
{
//存储视图模型供以后使用
}
//…实施
}
//App.Xaml中的设置代码
IUnityContainer unityContainer=新的unityContainer();
RegisterType(“LoadCommand”);
RegisterType(新的ContainerControlled LifetimeManager());
当我解析MainViewModel类时,我得到一个StackOverflow异常(如果VisualStudio返回)。现在我希望Unity先创建MainViewModel的实例,然后它基本上是一个单例,然后查看视图模型的实例并创建传入新创建的MainViewModel的命令,但显然我错了

有什么想法吗?

这是一个错误,正如上面所说,这是开发人员的责任来避免它。因此,MainViewModel对LoadCustomerCommand的引用是对MainViewModel->StackOverflow的引用

所以你唯一能做的就是

public class MainViewModel
{
    public MainViewModel()
    {
        Customers = new ObservableCollection<CustomerViewModel>();
    }        

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

    public ObservableCollection<CustomerViewModel> Customers { get; private set; }
}
public类主视图模型
{
公共主视图模型()
{
客户=新的可观察收集();
}        
//没有依赖关系。
公共ICommand LoaderCustomerCommand{get;set;}
公共可观测集合客户{get;private set;}
}
要解决此问题,您需要执行以下操作

var mainModel = unityContainer.Resolve<MainViewModel>();
mainModel.LoadCustomersCommand =     unityContainer.Resolve<ICommand>("LoadCommand");
var mainModel=unityContainer.Resolve();
mainModel.loadCustomerCommand=unityContainer.Resolve(“LoadCommand”);

感谢您的回答和链接。我认为可能是这样,但由于属性注入,我认为在实例化properties类时MainViewModel应该在容器中,而“循环”引用不会成为问题,但显然不是。谢谢你把它清理干净!