热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

这种情况适合DI吗?-IsthiscasesuitableforDI?

IamwritingaWPFsampleapp,andinthatIwanttodisplaylistofitemsinview.ViewhasMainVie

I am writing a WPF sample app, and in that I want to display list of items in view. View has MainViewModel which contains ObservableCollection. Clearly ItemViewModel is so specific that there's nothing to abstract from it.

我正在编写一个WPF示例应用程序,并且我希望在视图中显示项目列表。 View包含MainViewModel,其中包含ObservableCollection 。显然,ItemViewModel是如此具体,以至于没有任何东西可以从中抽象出来。

Question - When I build collection of these items in MainViewModel, is it OK to instantiate ItemViewModels manually, or should it be delegated to DI container?

问题 - 当我在MainViewModel中构建这些项的集合时,可以手动实例化ItemViewModel,还是应该委托给DI容器?

I am familiar with MVVM (and DI too), so point here is not whether to have ItemViewModel (I need it). But if DI still applies here, I seek clarifications.

我对MVVM(以及DI也是如此)很熟悉,所以这里指的不是是否有ItemViewModel(我需要它)。但如果DI仍适用于此,我会寻求澄清。

1 个解决方案

#1


0  

When I build collection of these items in MainViewModel, is it OK to instantiate ItemViewModels manually, or should it be delegated to DI container?

当我在MainViewModel中构建这些项的集合时,可以手动实例化ItemViewModels,还是应该委托给DI容器?

You could certainly construct the ItemViewModel objects "manually" using the new operator if that's what you are asking. There is nothing wrong with this approach. Why would you would you bother to use a container to create these if you don't have to?

你当然可以使用new运算符“手动”构造ItemViewModel对象,如果这就是你所要求的。这种方法没有错。如果你不需要,你为什么要费心用容器来创建它们呢?

If an ItemViewModel has some dependencies, the MainViewModel will also have these dependencies as it is the class that knows how to create ItemViewModels.

如果ItemViewModel有一些依赖项,MainViewModel也将具有这些依赖项,因为它是知道如何创建ItemViewModel的类。

So you could basically inject the MainViewModel with whatever dependencies it and the ItemViewModel class have.

所以你基本上可以为MainViewModel注入它和ItemViewModel类所具有的任何依赖关系。


推荐阅读
author-avatar
小肥沙沙2006_759
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有