2011-03-01 68 views
2

我已经配置容器:如何在Prism4 MEF中创建我的类的实例?

public class MyBootstrapper : MefBootstrapper 
{ 
    protected override void ConfigureAggregateCatalog() 
    { 
     AggregateCatalog.Catalogs.Add(xxx.Assembly)); 
// other assemblies 
    } 

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

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

我怎么能在模块中创建我的T类型的实例?类型T在程序集中的某处定义,由MEF配置。

我需要一些这样的:

var myType = XXXX.Resolve<T>(); 

UPD1。 MyModule的

[ModuleExport(typeof(CatalogModule))] 
public class CatalogModule : IModule 
{ 
    private readonly IEventAggregator _event; 
    private readonly IUIManager _uiManager; 

    [ImportingConstructor] 
    public CatalogModule(IEventAggregator @event, IUIManager uiManager) 
    { 
     _event = @event; 
     _uiManager = uiManager; 
    } 

    private void Foo() 
    { 
     var vm = **How create instance of desired type here?** 
    } 
} 

回答

3

你做同样的方式,你在CreateShell方法覆盖得到了MainWindow一个实例。您只需致电Container.GetExportedValue<T>()即可直接获取实例。但是,如果要为注入类型注入更多松散耦合,则需要具有一个构造函数,该属性取决于该类型(或者最好是接口),或者该类型的属性具有[Import]属性。

请确保您输入的类型是[Export]属性,并且该程序集已添加到AggregateCatalog

希望这有助于;)

+0

是的。 Buh我怎样才能得到'容器'?在模块中,我对此一无所知。 – Lari13 2011-03-01 13:31:17

+0

您可以让您的模块依赖于“CompositionContainer”类型的MEF Container(通过将其添加到“ImportingConstructor”中)。确保将自己的容器实例注册到引导程序中。 ('Container.ComposeExportedValue(容器);')。该容器将被注入到您的构造函数中,并且您将有权访问所有导出;) – AbdouMoumen 2011-03-01 13:54:43

+0

谢谢。现在我懂了 :) – Lari13 2011-03-01 14:04:47