2011-03-01 28 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