【问题标题】:How do I create instances of my classes in Prism4 MEF?如何在 Prism4 MEF 中创建我的类的实例?
【发布时间】:2011-03-01 11:37:14
【问题描述】:

我已经配置了容器:

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。 我的模块

[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?**
    }
}

【问题讨论】:

    标签: c# prism mef prism-4


    【解决方案1】:

    您执行此操作的方式与在 CreateShell 方法覆盖中获得 MainWindow 的实例相同。您只需拨打Container.GetExportedValue&lt;T&gt;(),即可直接获取实例。然而,如果你想注入一个类型,为了更松散的耦合,你需要一个构造函数和[ImportingConstructor] 属性,该属性依赖于该类型(或者最好是一个接口),或者该类型的属性具有一个[Import] 属性。

    通过使用[Export] 属性装饰类,确保已导出类型,并将程序集添加到AggregateCatalog

    希望这会有所帮助;)

    【讨论】:

    • 是的。 Buh我怎样才能得到'Container'?在模块中我对此一无所知。
    • 您可以让您的模块依赖于 CompositionContainer 类型的 MEF 容器(通过将其添加到 ImportingConstructor)。确保在引导程序中使用自身注册容器实例。 (Container.ComposeExportedValue(Container);)。容器将被注入到您的构造函数中,您将可以访问所有导出;)
    猜你喜欢
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多