【问题标题】:CompositionHost.Initialize() can not execute twiceCompositionHost.Initialize() 不能执行两次
【发布时间】:2011-06-28 05:46:26
【问题描述】:

我目前正在尝试集成 MEF 和 PRISM 以相互协作。到目前为止一切正常。现在我想使用 MEF 运行时模块发现 (DeploymentCatalog),它将用于从服务器目录下载 XAP,然后将其插入我的 MAIN UI 内的区域之一。

我正在使用 UnityBootStrapper,并且在这个类中我还集成了 MEF 容器。此示例应用程序基于 Glenn Block (http://codebetter.com/glennblock/2010/01/03/mef-and-prism-exploration-mef-module-loading/)。

以下代码用于在我的引导程序中初始化 CompositionContainer:

     // This is the host catalog which contains all parts of running assembly.
        var catalog = GetHostCatalog();

        // Create MEF container which initial catalog
        var container = new CompositionContainer(catalog);


        // here we explicitly map a part to make it available on imports elsewhere, using
        // Unity to resolve the export so dependencies are resolved
        // We do this because region manager is third-party ... therefore, we need to 
        // export explicitly because the implementation doesn't have its own [export] tag
        container.ComposeExportedValue<IRegionManager>(Container.Resolve<IRegionManager>());
        container.ComposeExportedValue<IEventAggregator>(Container.Resolve<IEventAggregator>());

        // Obtain CatalogService as a singleton
        // All dynamic modules will use this service to add its parts.
        Container.RegisterInstance<ICatalogService>(new CatalogService(catalog));


        // Initialize the container
        CompositionHost.Initialize(container);

现在我有另一个名为 DeploymentCatalogService 的类,用于从服务器下载 XAP。我目前面临的问题是在 DeploymentCatalogService Initialize 方法中,CompositionHost 容器尝试再次使用 aggregateCatalog 初始化其容器。

_aggregateCatalog = new AggregateCatalog();
        _aggregateCatalog.Catalogs.Add(new DeploymentCatalog());
        CompositionHost.Initialize(_aggregateCatalog);

这会导致一个异常,指出容器已被初始化。有没有办法使用现有容器并使用新的 aggregateCatalog 对其进行更新?

希望这不会太混乱。请客气,我还是 MEF 的新手。

干杯,

【问题讨论】:

    标签: mef


    【解决方案1】:

    您只能初始化容器一次。在您的情况下,您应该使用 AggregateCatalog 创建容器并存储对该目录的引用。然后稍后您可以将 DeploymentCatalog 添加到该 AggregateCatalog。

    【讨论】:

    • 使用您的想法,我创建了一个静态 CompositionHelper 类,它包含 CompositionContainer 和 AggregateCatalog。调用者可以通过 CompositionHelper 与 CompositionContainer 进行交互。通过这样做,我有一个中心位置来控制如何初始化容器以及使用相同的 AggegrateCatalog 添加新目录。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 2017-04-27
    • 2011-11-30
    相关资源
    最近更新 更多