Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up dependency injection with Caliburn Micro & Ninject

I'm trying to set up dependency injection in a new WPF project using the framework Caliburn Micro and Ninject. Unfortunately I'm not succeeding :( There are a few examples on the internet which implement a generic Bootstrap but for me the generic Bootstrap class is not available and since all these examples are at least 3 years old I guess they are deprecated...

What I've tried is the following:

public class CbmBootstrapper : BootstrapperBase
{
    private IKernel kernel;

    protected override void Configure()
    {
        this.kernel = new StandardKernel();

        this.kernel.Bind<IAppViewModel>().To<AppViewModel>();
    }
}

And in the App.xaml

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

I am very new to WPF and Ninject. Can you tell me what I have to change, so that at startup of the application, the View (AppView) with the corresponding ViewModel (AppViewModel) gets loaded?

Do you know of any up-to-date tutorial on using & setting up Ninject with Caliburn Micro?

like image 703
xeraphim Avatar asked Mar 16 '15 11:03

xeraphim


1 Answers

You will need to override OnStartup as well to have your root view / viewmodel shown:

protected override void OnStartup(object sender, System.Windows.StartupEventArgs e)
{
    DisplayRootViewFor<IAppViewModel>();
}

This extra call replaced the previous, generic bootstrapper and allows you to choose the root view for your application at runtime.

You'll also need to override GetInstance to have Caliburn hook into Ninject:

protected override object GetInstance(Type serviceType, string key)
{
    return container.Get(serviceType);
}

This is called by Caliburn.Micro whenever it needs to construct something, so it's your one-stop-shop for injecting Ninject (other IoC containers are available!) into the process.

As for an up-to-date tutorial; there aren't so many around since Caliburn.Micro went to version 2, however their official documentation is generally pretty useful.

EDIT: One more thing you have to do! Make sure that your bootstrapper constructor calls Initialize:

public CbmBootstrapper ()
{           
    Initialize();
}

This will kick Caliburn.Micro into action...

like image 90
Simon Cowen Avatar answered Oct 23 '22 11:10

Simon Cowen