您的位置:首页 > 其它

【Prism】MEF版HelloWorld

2015-07-22 21:06 387 查看
[b]引言[/b]

Pirsm框架是由微软P & P小组设计的,用于构建组合式的WPF企业级应用,支持两个IOC容器,分别为Unity和MEF.官方地址为http://compositewpf.codeplex.com/,在上面可以有最新的源码和Demo,其中多数Demo都是用Unity容器构建的,而本人比较喜欢MEF,打算把Unity的Demo全部改成MEF的,先从HelloWorld开始吧.

[b]模块HelloWorldModule[/b]

我们需要将HelloWorld.xaml先导出,,如下

[Export("HelloWorld")]
public partial class HelloWorld : UserControl
{
public HelloWorld()
{
InitializeComponent();
}
}


然后在HelloModule中做好Region和View的映射,映射有多种方式,我这里把其中一种注释掉,如下

[Export("HelloModule", typeof(IModule))]
public class HelloModule:IModule
{
private readonly CompositionContainer Container { get; set; }
private readonly IRegionManager RegionManager { get; set; }
private readonly IRegionViewRegistry RegionViewRegistry { get; set; }

[ImportingConstructor]
public HelloModule(CompositionContainer container, IRegionManager regionManager, IRegionViewRegistry registry)
{
Container = container;
RegionManager = regionManager;
RegionViewRegistry = registry;
}

public void Initialize()
{
HelloWorld HelloWorld = Container.GetExportedValue<HelloWorld>("HelloWorld");

IRegion mainRegion = RegionManager.Regions["MainRegion"];
mainRegion.Add(HelloWorld, "HelloWorld");

//  RegionViewRegistry.RegisterViewWithRegion("MainRegion", typeof(HelloWorld));

}
}


[b] 主程序PrismHelloWorld[/b]

在主程序中,我们需要继承MefBootstrapper,重写其中的几个方法,可以看到MEF的一个大优点,可以不引用的情况下加载模块程序集,如下

public class HelloWorldBootstrapper : MefBootstrapper
{

protected override void ConfigureAggregateCatalog()
{
//加载当前程序集
this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(HelloWorldBootstrapper).Assembly));

//加载模块目录中的DLL
DirectoryCatalog directoryCatalog = new DirectoryCatalog("Modules");
this.AggregateCatalog.Catalogs.Add(directoryCatalog);
}

protected override CompositionContainer CreateContainer()
{
CompositionContainer container = base.CreateContainer();
container.ComposeExportedValue(container); //这里将容器导出
return container;
}

protected override DependencyObject CreateShell()
{
return this.Container.GetExportedValue<Shell>();
}

protected override void InitializeShell()
{
base.InitializeShell();
Application.Current.MainWindow = (Shell)this.Shell;
Application.Current.MainWindow.Show();
}

protected override void InitializeModules()
{
//导出并初始化HelloModule
IModule moduleB = Container.GetExportedValue<IModule>("HelloModule");
moduleB.Initialize();
}
}


[b]部署[/b]
在主程序的启动目录下,新建Modules文件夹,将编译后的HelloWorldModule.dll丢进去,运行主程序,OK.

[b]示例源码[/b]

PrismHelloWorld.rar

[b]小结[/b]

示例比较简单,看代码即可明白,就不一一说明了.虽然是从最简单的HelloWorld改起,但是在学习Prism框架之前,必须对WPF基础,MEF容器,MVVM模式有一定了解,不然学起来一头雾水.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: