NET 6 - Dependency Injection

Last modified: March 25, 2022

ASP.NET 6 has a built-in dependency injection (DI) software design pattern, that is to achieve Inversion of Control (IOC) between classes and their dependencies. In a traditional ASP.NET without DI, do we as below  

public class AnimalService { private readonly MyDependency _dependency = new MyDependency(); public void OnGet() { _dependency.walk(); } }

The AnimalService class fully depends on MyDependency and should be avoided for the following reasons

  • If we want to replace MyDependency, then  AnimalService must be modified
  • if MyDependency  depends on something else, then it must be configured in AnimalService
  • Unit test is difficult to conduct.

Dependency injection solves these problems by following

  • By use of an interface to abstract the implementation
  • DI register in a service container and ASP.NET 6 has a built-in service container in Startup.ConfigureServices method.
  • Injection of service in the constructor when it is used and framework disposes of it when it is no longer needed.
Program.cs
  • In .NET 5 or before, we used to register a DI in Startup.cs file
  • However in .NET 6, we register a DI in Program.cs

In all free UI projects; MVC, Razor Pages, and Web API. Register the following Repositories

  • You need to add Core and Infrastructure projects to this.
builder.Services.AddScoped<IEventRepository, EventRepository>(); builder.Services.AddScoped<IEventBookingRepository, EventBookingRepository>();

di