With my blog I’ve several articles about dependency injection using Microsoft.Extensions.DependencyInjection. Now I’ve updated the source code of my older articles to .NET Core 2.1 and Visual Studio 2017. The articles cover Microsoft.Extensions.DependencyInjection, using the IOptions interface, using configuration (JSON files, XAML files, environmental variables…) with dependency injection, and also explain how to use scopes to automatically dispose injected services.
Here’s the list.
Dependency Injection with .NET Core
The first article in the series gives an overview on dependency injection, and demonstrates how to use Microsoft.Extensions.DependencyInjection:
Passing Options to Injected Services
Building upon the sample code of the first article, now parameters are passed to the injected service. To make this easy, .NET Core, defines the IOptions interface. The blog article explains how this can be done, and adds an enhancement with extension methods for easier use:
Configuring Services with Configuration Files
The third article in this series, based on the second one, makes use of a JSON configuration file to initialize injected services. Here, Microsoft.Extensions.Configuration is added to configure the options from the service:
Disposing Injected Services – Using Dependency Injection Scopes
A recent article explains the scopes when using Microsoft.Extensions.DependencyInjection with XAML-based applications (UWP, WPF, Xamarin), and shows how the dependency injection container manages the lifetime of services and disposes them automatically.
HTTP Client Factory with .NET Core 2.1
To see dependency injection in action, you should also read this article. Here, the HttpClientFactory (new with .NET Core 2.1) is configured to inject either
IHttpClientFactory with services.
Enjoy learning and programming!
My book Professional C# 7 and .NET Core 2.0 has a complete chapter on dependency injection, and makes use of DI in many chapters. DI is also covered with many of my workshops, no matter if it’s ASP.NET Core, WPF, UWP, or Xamarin.