Skip to content

Instantly share code, notes, and snippets.

@LwServices
Forked from sajidmohammed88/DI WPF-C#.md
Created June 27, 2022 16:35
Show Gist options
  • Save LwServices/da664d69d9d49d83afc495b12a04d091 to your computer and use it in GitHub Desktop.
Save LwServices/da664d69d9d49d83afc495b12a04d091 to your computer and use it in GitHub Desktop.
Dependency injection in WPF project with .net core

Dependency injection in WPF project with .net core

Delete StartupUri="MainWindow.xaml" from App.xaml
Install packages :
Microsoft.Extensions.Configuration.Json
Microsoft.Extensions.DependencyInjection
Microsoft.Extensions.Options.ConfigurationExtensions
Add the file appsettings.json in the root of the project to use it for configuration.
Override OnStartup method in App.Xaml.Cs class :
public IServiceProvider ServiceProvider { get; private set; }

public IConfiguration Configuration { get; private set; }

protected override void OnStartup(StartupEventArgs e)
{
    var builder = new ConfigurationBuilder()
     .SetBasePath(Directory.GetCurrentDirectory())
     .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

    Configuration = builder.Build();

    var serviceCollection = new ServiceCollection();
    ConfigureServices(serviceCollection);

    ServiceProvider = serviceCollection.BuildServiceProvider();

    var mainWindow = ServiceProvider.GetRequiredService<MainWindow>();
    mainWindow.Show();
}

private void ConfigureServices(IServiceCollection services)
{
    services.Configure<AppSettings>(Configuration.GetSection(nameof(AppSettings)));

    services.AddTransient(typeof(MainWindow));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment