Dependency injection without Ninject

落爺英雄遲暮 提交于 2019-12-24 03:48:17

问题


I've been reading up on dependency injection and what I understand from it is that you basically just pass instances from the top on 1 location (for example App.xml.cs down to the View, it ViewModel and the classes the ViewModel uses and so on.

Hopefully understanding this correctly I started trying to implement this.

I have a class 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 there looks like this:

ExceptionHandler(ILocalizer localizer, 
                 string logLocation)

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

MainWindowViewModel(IExceptionHandler exceptionHandler, 
                    ILocalizer localizer)

Before that my View will instantiate the ViewModel when it's 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'm stuck. I got the following exception:

'No matching constructor found on type 'Noru.Test.Views.MainWindowView'. You can use the Arguments or FactoryMethod directives to construct this type.' Line number '3' and line position '9'.

And inner exception:

No default constructor found for type 'Noru.Test.Views.MainWindowView'. You can use the Arguments or FactoryMethod directives to construct this type.


回答1:


It seems MainWindowView is startup view and as per code you provided in question View has only one constructor with parameter that means it does not have now any parameterless constructor. So you need to inform wpf about that

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()
    }


来源:https://stackoverflow.com/questions/29763594/dependency-injection-without-ninject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!