【发布时间】:2014-10-11 13:01:32
【问题描述】:
我正在启动一个新的桌面应用程序,我想使用 MVVM 和 WPF 构建它。
我也打算使用 TDD。
问题是我不知道应该如何使用 IoC 容器将我的依赖项注入到我的生产代码中。
假设我有以下类和接口:
public interface IStorage
{
bool SaveFile(string content);
}
public class Storage : IStorage
{
public bool SaveFile(string content){
// Saves the file using StreamWriter
}
}
然后我有另一个类具有 IStorage 作为依赖项,还假设这个类是 ViewModel 或业务类...
public class SomeViewModel
{
private IStorage _storage;
public SomeViewModel(IStorage storage){
_storage = storage;
}
}
有了这个我可以很容易地编写单元测试,以确保它们正常工作,使用模拟等。
问题在于在实际应用程序中使用它时。我知道我必须有一个 IoC 容器来链接 IStorage 接口的默认实现,但我该怎么做呢?
例如,如果我有以下 xaml 会怎样:
<Window
... xmlns definitions ...
>
<Window.DataContext>
<local:SomeViewModel />
</Window.DataContext>
</Window>
在这种情况下,如何正确“告诉”WPF 注入依赖项?
另外,假设我需要一个来自 C# 代码的 SomeViewModel 实例,我应该怎么做?
我觉得我完全迷失了,我会很感激任何关于如何处理它的最佳方式的例子或指导。
我熟悉 StructureMap,但我不是专家。另外,如果有更好/更简单/开箱即用的框架,请告诉我。
【问题讨论】:
-
使用 .net core 3.0 预览版,您可以使用一些 Microsoft nuget 包来实现。
标签: c# wpf mvvm dependency-injection dependencies