Home > .NET Core, C#, WPF > Using .NET Core 3.0 Dependency Injection and Service Provider with WPF

Using .NET Core 3.0 Dependency Injection and Service Provider with WPF

06/03/2019

Note: this article is based on a preview release of .NET Core 3.0, so this approach may change in the future.

We all know that .NET Core provides built-in support for Dependency Injection. We typically use it in ASP.NET Core (starting form the ConfigureServices method in the Startup.cs file), but the feature isn’t limited to this framework. So, as .NET Core 3.0 supports also Windows Clients development, we can use it in our WPF and Windows Forms applications.

Let’s see how to do that, for example, in WPF using Visual Studio 2019. Suppose we want to create a service and we also have some application settings; we want to pass both of them to each window of our application via Dependency Injection.

First of all, we must add the required NuGet packages to the project. Right click on the Solution Explorer, select the Manage NuGet Packages command and add the following packages (be sure to select the Include prerelease check):

  • Microsoft.Extensions.DependencyInjection
  • Microsoft.Extensions.Options.ConfigurationExtensions
  • Microsoft.Extensions.Configuration.Json
Adding Dependency Injection support to a .NET Core 3.0 WPF application

Adding Dependency Injection support to a .NET Core 3.0 WPF application

These packages are necessary to enable Dependency Injection support (the first one) and to store and retrieve application settings in the classic appsettings.json file (the other ones). They will automatically get all the required dependencies.

Then, let’s add a file named appsettings.json to the root folder of the project. Set its Build Action property to Content and Copy to Output Directory to Copy if newer:

{
  "AppSettings": {
    "StringSetting": "Value",
    "IntegerSetting": 42,
    "BooleanSetting": true
  }
}

All the prerequisites are met, so we can start writing our code. Let’s open the App.xaml file and remove the StartupUri property of the Application class. Then, we need to override the OnStartup method in App.xaml.cs:

public partial class App : Application
{
    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.AddTransient(typeof(MainWindow));
    }
}

In this method we create the Service Provider and configure the IoC container in a similar way of ASP.NET Core. We only need a bit of initialization. First of all, at line 9-13 we create an IConfiguration object that allows to read settings from the appsettings.json file (line 11). Then, we create an instance of a ServiceCollection class that will hold our services. Finally we call the ConfigureServices method (as we have in ASP.NET Core).

Within the latter (lines 24-29), we register all the services used by the application in the exact same way of ASP. NET Core. We’ll complete this method in a moment, but for now let’s notice that we register also the MainWindow class (line 28). This is important because, in this way, the window itself becomes part of the Dependency Injection chain. It means that, after calling this method, at line 20-21 we can get it from the ServiceProvider and then show it. But, more important, it means that we can pass to the MainWindow constructor all the dependencies it needs, as we do for ASP.NET Core Controllers.

Even if the actual services aren’t yet registered, we can run the application and see that everything works as expected.

Now it’s time to complicate the things a bit. First of all, let’s create an AppSettings.cs file to hold configuration settings. This file will map the settings that we write in appsettings.json:

public class AppSettings
{
    public string StringSetting { get; set; }

    public int IntegerSetting { get; set; }

    public bool BooleanSetting { get; set; }
}

Then, create also a sample service with its interface:

public interface ISampleService
{
    string GetCurrentDate();
}

public class SampleService : ISampleService
{
    public string GetCurrentDate() => DateTime.Now.ToLongDateString();
}

Now we must register these services in the IoC Container, as usual:

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

    // ...
}

As said before, the MainWindow itself is in the IoC Container. So, when we get it from the Service Provider, it will automatically be injected with all required services, if any. So, we just need to modify its constructor:

public partial class MainWindow : Window
{
    private readonly ISampleService sampleService;
    private readonly AppSettings settings;

    public MainWindow(ISampleService sampleService, 
                      IOptions<AppSettings> settings)
    {
        InitializeComponent();

        this.sampleService = sampleService;
        this.settings = settings.Value;
    }

    // ...
}

Running this code, we’ll obtain a result like the following:

The .NET Core 3.0 WPF application with dependencies injected

The .NET Core 3.0 WPF application with dependecies injected

You can download the sample app using the link below:

Using .NET Core 3.0 Dependency Injection and Service Provider with WPF

Advertisements
Categories: .NET Core, C#, WPF
  1. Mikhaël
    10/04/2019 at 09:15

    Thanks for the simple and complete sample!

    If you are using MVVM model, I think the best idea is to inject the viewmodel into your .xaml.cs ctor and set the DataContext to the injected instance

    • 10/04/2019 at 09:17

      Yes, you’re right. This is a basic example that shows how to Dependency Injection and Service Provider work with WPF on .NET Core 3.0, but of course you can apply these concepts in the scenario you want.

  2. Fernando
    30/05/2019 at 09:17

    Nice and concise sample. I just want to add that, if I am not mistaken, you don’t need to switch to .NET Core 3.0 yet if all you want is to use Microsoft’s dependency injection implementation. The Microsoft.Extensions.DependencyInjection package supports .NET Framework 4.6.1 too (at least the latest stable version to date, 2.2.0). I did a few tests and it seems to work for me.

  1. 07/03/2019 at 14:28
  2. 08/03/2019 at 08:38
  3. 13/03/2019 at 12:35
  4. 19/03/2019 at 19:54
  5. 13/05/2019 at 23:03
  6. 21/05/2019 at 15:31
Comments are closed.
%d bloggers like this: