将服务注入到启动窗口似乎很简单,因为我可以在App.xaml.cs中创建容器并从中解析。
我遇到的问题是如何将ViewModels和Services DI到User Controls中?用户控件是通过XAML标记实例化的,因此没有机会对它们进行
Resolve()
。我能想到的最好的方法是将容器放在一个Singleton中,并让用户控件从全局容器中解析其ViewModels。这感觉像是一种半途而废的解决方案,因为它仍然需要我的组件依赖于ServiceLocator。
完整的IoC在WPF中可行吗?
[编辑] - 已经建议使用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();
uc.VM = container.Resolve<AViewModel>();