Configuring dependency injection using Caliburn Micro & Ninject

I'm trying to set up dependency injection in a new WPF project using Caliburn Micro and Ninject framework. Unfortunately, I do not succeed :( There are several examples on the Internet that implement the common Bootstrap, but for me the common Bootstrap class is not available, and since all these examples are at least 3 years old, I think they are out of date ...

I tried 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 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 need to change so that when the application starts, the View (AppView) with the corresponding ViewModel (AppViewModel) is loaded?

Are you aware of any updated tutorial on using and configuring Ninject with Caliburn Micro?

+5
source share
1 answer

You will need to override OnStartup to display the root view / viewmodel:

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

This extra call has replaced the previous, common bootloader and allows you to choose the root mode for your application at runtime.

You also need to override GetInstance to have a Caliburn hook in Ninject:

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

This is called by Caliburn.Micro whenever it needs to create something, so this is where your one-stop shop for injecting Ninject (other IoC containers!) Enters.

As for the modern textbook; there are not many of them since Caliburn.Micro went to version 2, however, official documentation is usually very useful.

EDIT: Another thing you have to do! Make sure your bootstrapper constructor calls Initialize :

 public CbmBootstrapper () { Initialize(); } 

This will launch Caliburn.Micro in action ...

+2
source

Source: https://habr.com/ru/post/1215446/


All Articles