.net core WPF Dependency injection

185 Views Asked by At

I am new to WPF, I have created a simple WPF application that has a button, which on clicked will fetch data from database and give the output in textbox.

I have a issue in Dependency Injection, there is AppDBContext class for database, and logMessageService.cs which has the functionality for fetching data from DB.

private readonly ILogMessageService Service;

    public MainWindow(ILogMessageService service)
    {
        InitializeComponent();
        this.Service = service;
    }

I was given an error "No matching constructor found on type 'MainWindow'"

How to perform dependency injection in WPF?

1

There are 1 best solutions below

1
Phoenix Stoneham On

You'll want to use MVVM and create a MainWindowViewModel which you create in the Public MainWindow() constructor. The ViewModel can then either initialise the service itself, or your MainWindow constructor can initialise it and pass it as part of the constructor to the new view model.

Public MainWindow()
{
    InitialiseComponent();
    DataContext = new MainWindowViewModel(service);
}

Or

<Window x:Class="MainWindow"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:MyNameSpace">
<Window.DataContext>
    <local:MainWindowViewModel/>
</Window.DataContext>

...
</Window>

And

Public Class MainWindowViewModel
{
...
}