将服务传递给 MainViewModel - 我应该使用依赖项注入容器吗?
我有这样的代码:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var mainVM = new MainViewModel
(
new Service1(),
...
new Service10(),
);
var window = new MainWindow();
window.DataContext = mainVM;
window.Show();
}
}
我将所有服务实例传递给 MainViewModel。在 MainViewModel 中,我通过构造函数参数传递将这些服务传播到其他 ViewModel。
我应该为 App 类中的服务使用任何 DI 框架吗?
如果是,那么解析服务而不是手动创建实例有什么好处......?
I have this code:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var mainVM = new MainViewModel
(
new Service1(),
...
new Service10(),
);
var window = new MainWindow();
window.DataContext = mainVM;
window.Show();
}
}
I pass all my Services instances to the MainViewModel. Within the MainViewModel I spread those services to other ViewModels via constructor parameter passing.
Should I use any DI framework for the services in the App class?
If yes whats the benefit of resolving the services instead of just creating the instance manually... ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在容器中注册所有这些类型,并让
OnStartup
方法进行单个Resolve
调用。首先,让
MainWindow
在其构造函数中接受其视图模型:然后,在容器中与服务一起注册
MainWindow
和MainViewModel
。如果 MainViewModel 需要其他视图模型,请将它们放入其构造函数中并注册它们。最后,解析 MainWindow,它执行所有实例化工作:
这里的关键点是视图模型与您在容器中注册的任何其他类没有什么不同。
这种方法的优点(来自评论):
1)容器为您调用所有构造函数 - 您只需描述图形的每个部分,然后就可以完成组装它的繁琐过程。
2) MainViewModel 不必知道如何构造其子视图模型,这使其能够专注于其核心职责,而不必了解其子视图的每一个依赖关系。
You can register all of those types in the container, and have the
OnStartup
method make a singleResolve
call.First, have
MainWindow
accept its view model in its constructor:Then, register
MainWindow
andMainViewModel
in the container right alongside the services. IfMainViewModel
requires other view models, put those in its constructor and register them as well.Finally, resolve
MainWindow
, which performs all of the instantiation work:The key point here is that a view model is no different from any other class you would register in a container.
Advantages to this approach (from comments):
1) The container makes all the constructor calls for you - you simply have to describe each piece of the graph, and it goes through the tedium of assembling it.
2)
MainViewModel
is freed from having to know how to construct its child view models, which lets it focus on its core responsibilities instead of having to know every single depedency of its children.