【问题标题】:Caliburn.Micro + Autofac bootstrappingCaliburn.Micro + Autofac 引导
【发布时间】:2013-12-02 03:04:00
【问题描述】:

我有一个 Caliburn.Micro 项目,我正在尝试从它的 SimpleContainer 移植到 Autofac

我正在使用this code,这是this guide 中代码的更新版本。 使用 SimpleContainer 我只是做了(在引导程序内部)

protected override void OnStartup(object sender, System.Windows.StartupEventArgs e)
{
    this.DisplayRootViewFor<IScreen>(); // where ShellViewModel : Screen
}

现在这不再起作用了,那么我应该怎么做才能将 Autofac 与 Caliburn.Micro 集成?

【问题讨论】:

  • 发生了什么,您是遇到异常还是什么?请提供更多细节。谢谢。
  • 什么都没有。我注意到的奇怪的事情是它甚至没有触发 OnStartup 方法。理论上 DisplayRootViewFor 应该用 ShellViewModel 为 ShellView 调用 WindowManager.ShowDialog,但什么都没有显示。
  • 您是否使用未修改的链接中的引导程序?
  • 是的,来自 github。我刚刚添加了 onstartup 覆盖,就像我在使用 SimpleContainer 时所做的那样
  • 我唯一做的另一件事是创建一个普通的公共类 AppBootstrapper : AutofacBootstrapper { },在 App.cs 中我只做 var boot = new AppBootstrapper(); boot.Start();

标签: wpf mvvm dependency-injection autofac caliburn.micro


【解决方案1】:

您的解决方案存在一些问题。

首先,没有任何东西调用您的AppBootstrapper。这通常在 Caliburn.Micro 中通过将引导程序类型添加为 App.xaml 中的资源来完成。有关 WPF 的说明,请参阅 here

即你的App.xaml 应该是这样的:

<Application x:Class="AutofacTests.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
         xmlns:local="clr-namespace:AutofacTests">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary>
                    <local:AppBootstrapper x:Key="bootstrapper" />
                </ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

其次,由于您的视图模型和视图位于不同的程序集中,Caliburn.Micro 和 Autofac 都需要知道它们的位置(分别用于视图位置和依赖关系解析)。

您正在使用的 Autofac 引导程序解析来自 Caliburn.Micro 用于查看位置的 AssemblySource 实例的依赖关系。因此,您只需填充此程序集源集合。您可以通过在 AppBootstrapper 中覆盖 SelectAssemblies 来做到这一点:

protected override IEnumerable<Assembly> SelectAssemblies()
{
    return new[]
               {
                   GetType().Assembly, 
                   typeof(ShellViewModel).Assembly, 
                   typeof(ShellView).Assembly
               };
}

【讨论】:

  • 正如我所写的,正如您在附加的解决方案中看到的那样,我创建了一个新的引导程序并在 app.cs 中对其调用 start,无论如何,现在我会尝试您的建议
  • 我覆盖了 SelectAssemblies 方法,但没有任何改变,您能看看我的解决方案并告诉我它需要的确切编辑吗?谢谢
  • 这些是您需要的确切更改,我自己对您的解决方案进行了更改。您是否对 App.xaml 进行了更改?您的 SelectAssemblies 是否在 AppBootstrapper 中?
  • 现在我创建了另一个项目,将引导程序、视图和视图模型都放在同一个程序集中,现在我可以正常工作了。我将尝试将事物分开,让我们看看
  • 我成功了!我不明白为什么,但我仍然在 App.xaml 引导程序资源定义上收到一个奇怪的错误,说它无法找到 System.Core 版本 2.0.5.0,但除此之外,它可以工作!谢谢你们!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-15
  • 2023-03-07
  • 2015-12-15
  • 2023-04-03
  • 2016-10-19
相关资源
最近更新 更多