Ada*_*dam 6 c# dependency-injection unity-container mvvm
我已经使用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());
Run Code Online (Sandbox Code Playgroud)
当我解析MainViewModel类时,我得到一个StackOverflow异常(如果Visual Studio完全回来的话).现在我希望Unity首先创建一个MainViewModel实例,因为它基本上是一个单例,然后查看View Model的实例并创建在新创建的MainViewModel中传递的Command,但显然我错了.
有任何想法吗?
这是循环引用错误,正如它所说,开发人员有责任避免它.所以MainViewModel引用了LoadCustomersCommand,它引用了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; }
}
Run Code Online (Sandbox Code Playgroud)
并解决你需要做以下事情
var mainModel = unityContainer.Resolve<MainViewModel>();
mainModel.LoadCustomersCommand = unityContainer.Resolve<ICommand>("LoadCommand");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3451 次 |
| 最近记录: |