Dependency Injection

What is dependency Injection?

Dependency Injection (DI) is a design pattern used to achieve loose coupling between components in an application. In ASP.NET Core MVC, DI is built-in and is used to inject dependencies into classes, rather than having the classes create or find their own dependencies.

In DI, dependencies are registered with the DI container, which is responsible for resolving and providing the dependencies to the requesting classes.

This allows for a more modular and maintainable application architecture, as well as easier unit testing of individual components.

For example, to inject a service into a controller, you would define a constructor for the controller that accepts the service as a parameter, like this:

public class MyController : Controller
{
    private readonly IService _service;

    public MyController(IService service)
    {
        _service = service;
    }

    // Controller actions here...
}

Then, in the ConfigureServices method of the Startup class, you would register the service with the DI container like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IService, MyService>();
    // Other configuration here...
}

The AddScoped method registers the service with the DI container as a scoped dependency, meaning that a new instance of the service will be created for each request. Other dependency lifetimes are also available, such as AddSingleton for a single instance across the entire application, and AddTransient for a new instance for each injection.

Overall, DI is a powerful technique for building maintainable, testable, and flexible applications in ASP.NET Core MVC.

My small demo

Last updated