Wpf Unity Bootstrapper my configure容器在调用视图模型时不工作
我使用棱镜6.1。我在Wpf Unity Bootstrapper my configure容器在调用视图模型时不工作,wpf,dependency-injection,unity-container,prism,Wpf,Dependency Injection,Unity Container,Prism,我使用棱镜6.1。我在Bootstrapper类的方法ConfigureContainer中设置了Unity配置。但是,当Prism框架尝试调用视图模型时,它无法创建该模型,并抛出异常“没有为此对象定义无参数构造函数” Bootstrapper.cs public class Bootstrapper: UnityBootstrapper { ... protected override void ConfigureContainer() { base.C
Bootstrapper
类的方法ConfigureContainer
中设置了Unity配置。但是,当Prism框架尝试调用视图模型时,它无法创建该模型,并抛出异常“没有为此对象定义无参数构造函数”
Bootstrapper.cs
public class Bootstrapper: UnityBootstrapper
{
...
protected override void ConfigureContainer()
{
base.ConfigureContainer();
this.Container.RegisterType<IMyService, MyService>(new ContainerControlledLifetimeManager());
this.Container.RegisterType<MyFormViewModel>(new ContainerControlledLifetimeManager());
}
...
}
MyFormViewModel.cs
public class MyFormViewModel : BindableBase
{
private readonly IMyService myService;
public SkypeActionViewModel(IMyService myService)
{
this.myService = myService;
}
...
}
在这一行中,抛出异常:
regionViewRegistry.RegisterViewWithRegion("MainRegion", typeof(Views.MyFormView));
中解释了如何配置unity,但这是在模块类中(在我的示例中是MyFormModule
)。我不理解这一点,因为这样,我需要在每个模块中配置它,而我的模块类中没有对象this.container.RegisterType
在其他链接中,我发现了一些类似于“MEF”配置的配置,其中“DI”配置位于ConfigureContainer
方法中。但它不适用于我的,或者我的配置中缺少一些东西
编辑
我将容器包括在我的模块类中。但我也有同样的问题。我认为这是正常的,因为问题是当Prism创建视图模型类时
public class MyFormModule : IModule
{
private readonly IRegionViewRegistry regionViewRegistry;
private readonly IUnityContainer container;
public MyFormModule(IRegionViewRegistry registry, IUnityContainer container)
{
this.regionViewRegistry = registry;
this.container = container;
}
public void Initialize()
{
this.container.RegisterType<IMyService, MyService>(new ContainerControlledLifetimeManager());
this.container.RegisterType<MyFormViewModel>();
this.container.RegisterType<MyFormView>();
regionViewRegistry.RegisterViewWithRegion("MainRegion", typeof(MyFormView));
}
}
然后,在Bootstrap
类中的方法ConfigureViewModelLocator
中调用所有视图模型,以将其与视图绑定:
protected override void ConfigureViewModelLocator()
{
BindViewModelToView<ViewAVM, ViewA>();
BindViewModelToView<ViewAVM, ViewB>();
}
protected override void ConfigureViewModelLocator()
{
BindViewModelToView();
BindViewModelToView();
}
如何告诉prism创建视图模型?您是否正在使用ViewModelLocator.AutoWireViewModel=“True”
如果是这样的话,你想做类似的事情
ViewModelLocationProvider.SetDefaultViewModelFactory( type =>
{
return Container.Resolve(type);
});
在引导程序中,确保容器用于解析视图模型…您可以像任何其他依赖项一样将容器注入到模块定义类中,以便您的模块可以像引导程序一样调用
container.RegisterType
。对于IRegionManager
…@Haukinger,我在模块类中包括了一个IUnityContainer
,但我有同样的问题。我没有使用ViewModelLocator.AutoWireViewModel=“True”
。但我找到了解决办法。我将创建一个答案。很抱歉,是的,我正在XAML文件中使用ViewModelLocator.AutoWireViewModel=“True”
protected override void ConfigureViewModelLocator()
{
BindViewModelToView<ViewAVM, ViewA>();
BindViewModelToView<ViewAVM, ViewB>();
}
ViewModelLocationProvider.SetDefaultViewModelFactory( type =>
{
return Container.Resolve(type);
});