C#C
C#3y ago
47 replies
zynthh

❔ ✅ Trouble getting Dependency Injection to work in a WPF application

Hi, I think I'm losing my mind. I cannot get DI to work in my WPF application. What I'm trying to do is, inject a DbContext into a custom service class which is injected into a Page.


Page:
public partial class SomePage : Page
{
    private readonly ISomeService _someService;

    public SomePage(ISomeService someService)
    {
        InitializeComponent();
        _someService = someService;
    }
}


Service:
public class SomeService : ISomeService
{
    private readonly DataContext _context;

    public SomeService(DataContext context)
    {
        _context = context;
    }
}

Application DI setup:
using app.Data;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Windows;
using app.Services;

namespace app;

public partial class App : Application
{
    public static IHost? AppHost { get; private set; }

    public App()
    {
        AppHost = Host.CreateDefaultBuilder()
            .ConfigureServices((hostContext, services) =>
            {
                services.AddSingleton<MainWindow>();
                services.AddDbContext<DataContext>();
                services.AddSingleton<ISomeService, SomeService>();
            })
            .Build();
    }

    protected override async void OnStartup(StartupEventArgs e)
    {
        await AppHost!.StartAsync();

        var startupForm = AppHost.Services.GetRequiredService<MainWindow>();
        startupForm.Show();

        base.OnStartup(e);
    }

    protected override async void OnExit(ExitEventArgs e)
    {
        await AppHost!.StopAsync();
        base.OnExit(e);
    }
}


When I try to build the app I get the attached error.

I don't know how to debug this, it's probably something very obvious to some of you. Any help would be greatly appreciated!
image.png
Was this page helpful?