C#C
C#11mo ago
wildREA

Manually Showing MainWindow.xaml In App.xaml.cs (Dependency Injection)

Hey! My code is supposed to manually show MainWindow.xaml, but it doesn't if I remove StartupUri="MainWindow.xaml" and I get the error that is listed with details below with it. Without it, I get no error, so it must be my logic. The way I wrote it is because of dependency injection for AppLanguageServices.

App.xaml

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


App.xaml.cs

private static IServiceProvider? ServiceProvider;

protected override void OnStartup(StartupEventArgs e)
{
    var serviceCollection = new ServiceCollection();

    // Register services
    serviceCollection.AddSingleton<IAppLanguageServices, AppLanguageServices>();
    serviceCollection.AddTransient<ComponentUsage>();
    serviceCollection.AddTransient<MainWindow>();
    serviceCollection.AddTransient<Settings>();

    // Build service provider
    ServiceProvider = serviceCollection.BuildServiceProvider();

    // Manually create and show MainWindow
    var mainWindow = ServiceProvider.GetRequiredService<MainWindow>();
    mainWindow?.Show();

    base.OnStartup(e);
}
Was this page helpful?