Member-only story
.NET Core dependency injection (DI)
Why Dependency Injection?
Instantiate objects are done with a call to the constructor via the new operator. This invocation forces a tightly couple connection between classes. We can say that is a hardcoded reference.
Imagine the following scenario, an application using Serilog for logging. The application has hardcoded references to the service that is responsible to write to logs. Now, for some reason, your company decided to switch from Serilog do NLog. You need to mess up with the code of the entire application just because of this change.
Rather than asking the service collection for a specific type (tightly coupled reference), you will instead ask a service collection or factory for the instance.
In this case, you are going to ask for an interface, such as ILogger, and you don’t care which provider is being used (NLog or Serilog). Simple right? avoiding tightly coupled classes. And the best part, for the requested change you just need to change the DI register.
No references to the direct implementation will be needed
Now technically the actual name for this pattern is Inversion of Control.
.NET Core DependencyInjection
All you need is a reference to Microsoft.Extensions.DependencyInjection.Abstractions NuGet package. Then, you have access to IServiceCollection interface, which expose…