Using DI containers
A DI container is a library that injects a service into the client. A DI container provides extra functionality other than injecting dependencies, such as the following:
- Registering the classes that need to be injected (registering the services)
- Implementing how the services need to be instantiated
- Instantiating what has already been registered
- Managing the created service lifetime
Let’s clarify a DI container role with an example from the previous code. We have the logger
service being injected, but who is responsible for this?
There is a DI container called Microsoft.Extensions.DependencyInjection
that will inject _logger
. This happened in the first line of Program.cs
, as illustrated here:
var builder = WebApplication.CreateBuilder(args);
This previous method call registers a default logger. Unfortunately, while we can see the code in the .NET source code, it is not obvious in our Program.cs
source code. In fact, the...