我已经使用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");
原文地址:https://www.jb51.cc/csharp/243875.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。