关于视图模型和接口
我正在开发 WPF Prism 应用程序,一切正常。我的视图模型都有接口,由 MEF 注入。
但是,我并不真正理解视图模型接口的好处。毕竟,视图与其视图模型相关联,所以我认为永远不会有其他实现。
其实我的观点也有接口。看来这也是大材小用了?
所以我的问题是:我不能删除所有视图和视图模型接口并直接注入视图和视图模型吗?有什么理由保留视图和视图模型的接口吗?
谢谢, L
I'm developing a WPF Prism application, and everything is working fine. My view models all have interfaces, which are injected by MEF.
However, I don't really understand the benefit of interfaces for view models. After all, a view is tied to its view model, so I think there will never be other implementations.
Actually, I also have interfaces for my views. It seems that this is also overkill?
So my question is: can't I just remove all view and view model interfaces and inject the views and view models directly? Is there any reason to keep interfaces for views and view models?
Thx,
L
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一种矫枉过正的行为。我知道您可能想模拟您的 ViewModel,但我认为实用更重要。另外,为什么您甚至需要模拟您的 ViewModel?恕我直言,任何需要模拟的逻辑都应该放入服务类中。
It is an overkill. I understand that you may want to mock your ViewModels, but I think it's more important to be practical. Plus, why would you even need to mock your ViewModels? Any logic that needs to be mocked should be put into a service class IMHO.
连接您的 ViewWModel 可以给您带来在测试中模拟它们的好处,连接您的视图看起来确实有点矫枉过正。您不会交换视图,并且可以在 ViewModel 的模拟上完成 UI 测试,因此我认为您实际上不需要与它们进行交互。
Interfacing your VieWModels gives you the benefit of mocking them in a test, interfacing your Views looks like some overkill indeed. You won't interchange your views and UI testing can be done on mocks of your ViewModel so you won't really need to interface them I think.
我能想到的 ViewModel 接口的最大原因是,您可以编写实现这些接口的模拟,以便在单元测试时使用。由于一个 ViewModel 可以与另一个 ViewModel 通信,因此您可以在测试第一个 ViewModel 时消除第二个 ViewModel 的行为。
MVVM 模式使对类进行单元测试变得更加容易,因为它将数据和控制与 UI 层分离(很难为其编写单元测试)。就我个人而言,我不会为我的观点编写界面。
The biggest reason I can think of for interfaces for ViewModels would be that you can write mocks that implement those interfaces for use while unit testing. Since one ViewModel may talk to another, it enables you to stub out the second ViewModels behaviour when testing the first.
The MVVM pattern makes it easier to unit test the classes as it separates data and control from the UI layer (which is harder to write unit tests for). Personally, I don't write interfaces for my views though.