WPF 中何时初始化依赖注入对象?
我正在尝试了解 WPF 中的依赖注入概念。如果我有一个对话框,其中的 ViewModel 定义为依赖注入,那么在运行时的什么时候,依赖注入的 ViewModel 会被初始化并给出一个值?是在对话框的构造函数中调用Initialize()方法期间吗?
public partial class LoginDialog
{
private LoginViewModel _loginViewModel;
[Dependency]
public LoginViewModel LoginViewModel
{
get { return _loginViewModel; }
set
{
...
}
}
public LoginDialog()
{
InitializeComponent();
}
}
I'm trying to wrap my head around the dependency injection concept in WPF. If I have a Dialog that has a ViewModel defined as being dependency injected, at what point during runtime is the dependency injected ViewModel initialized and given a value? Is it during the Initialize() method that is called in the Constructor of the Dialog?
public partial class LoginDialog
{
private LoginViewModel _loginViewModel;
[Dependency]
public LoginViewModel LoginViewModel
{
get { return _loginViewModel; }
set
{
...
}
}
public LoginDialog()
{
InitializeComponent();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的问题的答案是:这取决于(没有双关语)。这取决于很多事情,您使用哪个 DI 框架(Unity、Ninject 等)?在 Unity 中(我对此有更多经验),您必须定义对象的生命周期范围,并且根据它的生命周期,您可能会在不同的时间完成任务。
更具体地说:通常,当实例化定义它的对象时,您所演示的依赖属性将被“设置”。因此,当实例化
LoginDialog
时,应设置LoginViewModel
。The answer to your question is: It depends (no pun intended). It depends on a lot of things, which DI framework are you using (Unity, Ninject, etc)? In Unity (I have more experience with this one) you have to define what the lifetime scope of an object is, and depending on it's lifetime, you may get things done at different times.
To try to be more specific: Generally, a dependency property as you demonstrated there, will be "set" when the object on which it is defined is instantiated. So when your
LoginDialog
is instantiated, theLoginViewModel
should be set.