Ninject Injection Injection

I read about dependency injection, and I understand that you just simply pass instances from the top from 1st place (e.g. App.xml.cs to View, ViewModel and classes that ViewModel uses, etc.

I hope I understood this correctly, I started trying to implement this.

I have a Localizer : ILocalizer with the following constructor:

 Localizer(ResourceDictionary appResDic, string projectName, string languagesDirectoryName, string fileBaseName, string fallbackLanguage) 

I also have an ExceptionHandler : IExceptionHandler that uses this class, so my constructor looks like this:

 ExceptionHandler(ILocalizer localizer, string logLocation) 

Now for the ViewModel. ViewModel uses both Localizer and ExceptionHandler , so my contractor looks like this:

 MainWindowViewModel(IExceptionHandler exceptionHandler, ILocalizer localizer) 

Prior to this, my View will instantiate the ViewModel when called with the following constructor.

 public MainWindowView(IExceptionHandler exceptionHandler, ILocalizer localizer) { InitializeComponent(); MainWindowViewModel viewModel = new MainWindowViewModel(exceptionHandler , localizer); this.DataContext = viewModel; } 

This is where I am stuck. I got the following exception:

'There is no matching constructor found in the type "Noru.Test.Views.MainWindowView". You can use the Arguments or FactoryMethod directives to build this type. 'Line number "3" and line position "9".

And an internal exception:

There is no default constructor for the type "Noru.Test.Views.MainWindowView". You can use the Arguments or FactoryMethod directives to create this type.

+2
c # dependency-injection wpf mvvm
source share
1 answer

MainWindowView seems to be the initial view and according to the code you provided in the question. View has only one constructor with a parameter, which means that it now has no constructor without parameters. So you need to tell wpf about it

in App.xaml

 <Application x:Class="WpfApplication1.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Startup="App_OnStartup" > <Application.Resources> </Application.Resources> </Application> 

in app.xaml.cs (code behind)

  private void App_OnStartup(object sender, StartupEventArgs e) { var mainWindowView = new MainWindowView(localizer); <--- you need to inject constructor argument here. mainWindowView.Show() } 
+1
source share

All Articles