我想在我的WPF应用程序中开始使用依赖注入,主要是为了更好的单元可测试性.我的应用程序主要是按照MV-VM模式构建的.我正在为我的IoC容器看autofac,但我认为这对于这个讨论来说并不重要.
将服务注入启动窗口似乎很简单,因为我可以在App.xaml.cs中创建容器并从中解析它.
我正在努力的是如何将DI ViewModels和服务转化为用户控件?用户控件通过XAML标记实例化,因此没有机会Resolve().
我能想到的最好的方法是将容器放在Singleton中,让用户控件从全局容器中解析它们的ViewModel.这感觉就像是一个中途解决方案,充其量,因为它仍然需要我的组件依赖于ServiceLocator.
WPF可以完全使用IoC吗?
[编辑] - 有人建议使用Prism,但即使是对Prism进行评估也似乎是一笔巨大的投资,我希望能有更小的东西
[编辑]这是我停止的代码片段
//setup IoC container (in app.xaml.cs)
var builder = new ContainerBuilder();
builder.Register<NewsSource>().As<INewsSource>();
builder.Register<AViewModel>().FactoryScoped();
var container = builder.Build();
// in user control ctor -
// this doesn't work, where do I get the container from
VM = container.Resolve<AViewModel>();
// in app.xaml.cs
// this compiles, but I can't use this uc,
//as the one I want in created via xaml in the primary window
SomeUserControl uc = new SomeUserControl(); …Run Code Online (Sandbox Code Playgroud) wpf design-patterns dependency-injection inversion-of-control autofac