我正在使用 Prism 和 Unity 创建一个应用程序。我使用DirectoryModuleCatalog
来从磁盘加载几个模块,这些模块显示在主菜单中,当您单击此特定模块的名称时,该模块的 UI 将被加载。每个模块都是根据 MVVM 模型设计的,因此具有单独的视图和视图模型。
引导程序:
class Bootstrapper : UnityBootstrapper
{
protected override DependencyObject CreateShell()
{
Shell shell = Container.Resolve<Shell>();
shell.Show();
return shell;
}
protected override void InitializeShell()
{
base.InitializeShell();
App.Current.MainWindow = (Window)this.Shell;
App.Current.MainWindow.Show();
}
protected override void ConfigureContainer()
{
base.ConfigureContainer();
Container.RegisterType<IApplicationMenuRegistry, MenuRegistry>();
Container.RegisterType<IApplicationCommands, ApplicationCommands>();
Container.RegisterType<ShellViewModel, ShellViewModel>(new Microsoft.Practices.Unity.ContainerControlledLifetimeManager());
//****** When I uncomment following line, the HelloWorldModule2 doesn't get initialized ***********
// Container.RegisterType<HelloWorldModule2ViewModel, HelloWorldModule2ViewModel>(new Microsoft.Practices.Unity.ContainerControlledLifetimeManager());
}
protected override IModuleCatalog CreateModuleCatalog()
{
return new DirectoryModuleCatalog() { ModulePath = @"C:\Data\NPC Service Tool\Source\develop\POC\GUIWithPrism\Modules" };
}
}
模块:
namespace HelloWorldModule2
{
[Module(ModuleName="HelloWorldModule2")]
public class HelloWorldModule2 : IModule
{
private IApplicationMenuRegistry menuRegistry;
private HelloWorldModule2ViewModel viewModel;
private IRegionManager regionManager;
public HelloWorldModule2(IApplicationMenuRegistry menuRegistry, HelloWorldModule2ViewModel vm, IRegionManager regionManager)
{
this.menuRegistry = menuRegistry;
this.regionManager = regionManager;
this.viewModel = vm;
}
public void Initialize()
{
ObservableCollection<ViewObject> views = new ObservableCollection<ViewObject>();
views.Add(new ViewObject() { Region = RegionName.Right, ViewType = typeof(HelloWorld2View) });
views.Add(new ViewObject() { Region = RegionName.Left, ViewType = typeof(View2) });
//****** Here the module gets registered in the main menu ******//
menuRegistry.RegisterModuleMenuItem("HelloWorld2", "Hello World module 2",views,1);
this.viewModel.Title = "Hello world module 2";
}
}
}
查看型号:
namespace HelloWorldModule2.ViewModels
{
public class HelloWorldModule2ViewModel : NotificationObject
{
private string title;
public string Title
{
get { return title; }
set
{
title = value;
RaisePropertyChanged(() => this.Title);
}
}
}
}
我遇到了以下问题:当我在 Bootstrapper 代码中看到的 Unity 容器中注册视图模型时,我的模块没有被初始化(我在Initialize
模块的方法中设置了一个断点,但它从未命中)。如果我删除注册并删除模块构造函数中的 vm 参数,则模块会初始化。
此外,当我使用此模块手动配置模块目录时:
protected override void ConfigureModuleCatalog()
{
base.ConfigureModuleCatalog();
ModuleCatalog moduleCatalog = (ModuleCatalog)this.ModuleCatalog;
moduleCatalog.AddModule(typeof(HelloWorldModule2.HelloWorldModule2));
}
而不是 ,DirectoryModuleCatalog
即使注册了视图模型,它也会正确初始化。