Caliburn.Micro和MEF在WPF上的应用

13

我正在学习WPF和Caliburn.Micro。我正在跟随这里介绍的代码:http://caliburnmicro.codeplex.com/wikipage?title=Customizing%20The%20Bootstrapper&referringTitle=Documentation

显然,这段代码是为Silverlight编写的,但我的项目是WPF,因此我会遇到“未定义CompositionHost”的错误。

该文档指出,我需要直接在WPF中初始化容器,但没有文档来展示如何操作。那么我应该如何直接初始化容器呢?

编辑1 文档中的引导程序如下:

     container = CompositionHost.Initialize(
        new AggregateCatalog(
            AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>()
            )
        );

    var batch = new CompositionBatch();

    batch.AddExportedValue<IWindowManager>(new WindowManager());
    batch.AddExportedValue<IEventAggregator>(new EventAggregator());
    batch.AddExportedValue(container);

    container.Compose(batch);

我进行了转换:

    var catalog =
            new AggregateCatalog(
                AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>());

        this.container = new CompositionContainer(catalog);
        var batch = new CompositionBatch();

        batch.AddExportedValue<IWindowManager>(new WindowManager());
        batch.AddExportedValue<IEventAggregator>(new EventAggregator());
        batch.AddExportedValue(this.container);

        this.container.Compose(batch);

但当我运行应用程序时,我遇到了一个错误,MEF无法找到IShell的实现

     Could not locate any instances of contract IShell.

我认为我的MEF初始化不正确。你能帮我修正一下吗?

1个回答

17

在WPF中,您需要使用显式的CompositionContainer构造函数。在我的WPF和Silverlight共享的引导程序中,我使用了以下的#if-#else指令:

#if SILVERLIGHT
    container = CompositionHost.Initialize(catalog);
#else
    container = new CompositionContainer(catalog); ;
#endif

编辑

引导程序将识别实现了 IShell 接口的组件(前提是您的引导程序扩展了 Bootstrapper<IShell> 基类),因此您需要实现一个带有 MEF 导出 IShell 的类。

通常这将是您的 ShellViewModel,声明如下:

[Export(typeof(IShell))]
public class ShellViewModel : PropertyChangedBase, IShell
{
   ...
}

你可以在这里了解更多关于引导程序设置和自定义方面的内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接