-->

Caliburn.Micro + Autofac bootstrapping

2020-07-17 14:35发布

问题:

I have a project with Caliburn.Micro, and I'm trying to port from its SimpleContainer to Autofac.

I'm using this code, that is an updated version of the code in this guide. Using SimpleContainer I simply did (inside the bootstrapper)

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

Now this doesn't work anymore, so what should I do to integrate Autofac with Caliburn.Micro ?

回答1:

There are a couple of things wrong with your solution.

Firstly, nothing invokes your AppBootstrapper. This is normally done in Caliburn.Micro by adding your bootstrapper type as a resource in App.xaml. See here for the instructions for WPF.

i.e. your App.xaml should look like this:

<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>

Secondly, as your view models and views are in different assemblies, both Caliburn.Micro and Autofac will need to know where they are located (for view location and dependency resolution respectively).

The Autofac bootstrapper you are using resolves dependencies from the AssemblySource instance that Caliburn.Micro uses for view location. Therefore, you just need to populate this assembly source collection. You do this by overridding SelectAssemblies in your AppBootstrapper:

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