© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•13mo ago•
147 replies
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"
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">
<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);
}
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);
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements
Next page

Similar Threads

Dependency injection
C#CC# / help
6mo ago
✅ Dependency injection
C#CC# / help
2y ago
❔ Dependency Injection
C#CC# / help
3y ago
Dependency injection in WPF
C#CC# / help
3y ago