嵌套视图模型上的IOC容器(IOC container on nested view models)

编程入门 行业动态 更新时间:2024-10-27 03:27:36
嵌套视图模型上的IOC容器(IOC container on nested view models)

我正在开发一个WPF应用程序,试图尽可能地遵守MVVM模式,包括DI和IoC。 该应用程序的结构为“ViewModel first”,其中可视层次结构包含以下内容:

MainView |-Login View |-Content View |-Content A |-Content B |-Content x

每个视图都由其VM引用; “MainViewModel”和“ContentViewModel”公开了一个引用子VM的属性来控制内部元素的导航。 这就是说,“内容A”,“内容B”和类似项目依赖于我想通过DI管理的各种服务。

我使用UnityContainer并在“OnStartup”中注册所有依赖项,但这里出现了我的问题:因为我不想使用ServiceLocator如何让“sub-viewmodels”知道容器? 我很确定我在理论方面做错了什么但我没有在网上找到任何参考。 我在网上找到的每个教程/示例都只是在容器中注册依赖项,然后立即解析模型。


I'm developing a WPF application trying to adhere as much as possible to MVVM patterns, including DI and IoC. The application is structured as "ViewModel first" where the visual hierarchy contains what follows:

MainView |-Login View |-Content View |-Content A |-Content B |-Content x

Each view is referenced by its VM; "MainViewModel" and "ContentViewModel" expose a property which references the child VM to control the navigation of the inner elements. That said "Content A", "Content B" and similar items have dependencies on various services which I would like to manage through DI.

I use a UnityContainer and I register all the dependencies in the "OnStartup" but here it comes my question: as I don't want to use a ServiceLocator how can I make the "sub-viewmodels" aware of the container? I'm pretty sure I'm doing something wrong theory-side but I haven't found any reference online. Each tutorial/example I found online just register the dependencies in the container and then immediately resolve the models.


最满意答案

由于父视图模型可以访问容器并负责创建任何子视图模型,因此当您在父视图模型中实例化子视图模型时,可以简单地将子视图模型注入到对容器的引用中:

this.ChildViewModelProperty = new ChildViewModel(_container);

这是构造函数依赖注入的典型示例。

Since a parent view model has access to the container and is responsible for creating any child view models, you could simply inject the child view models with a reference to the container when you instantiate them in the parent view model:

this.ChildViewModelProperty = new ChildViewModel(_container);

This is a typical example of constructor dependency injection.

更多推荐

本文发布于:2023-08-07 22:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466457.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   视图   容器   模型   view

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!