How to implement Dependency injection in .NET Core?

Dependency Injection (DI) is a fundamental design pattern in .NET Core and .NET 5+ that allows you to inject dependencies into classes rather than having those classes create their dependencies. This promotes loose coupling, testability, and maintainability in your code. Here's how you can implement Dependency Injection in .NET Core:

Define Your Dependencies:

Start by defining the interfaces or abstract classes for your dependencies. These are the services or components that you want to inject into your classes.

public interface IMyService
{
    void DoSomething();
}

Implement Dependency Classes:

Create concrete implementations of your dependency interfaces or classes.

public class MyService : IMyService { public void DoSomething() { // Implementation } }

Configure Dependency Injection:

In your startup class (usually Startup.cs), configure the DI container in the ConfigureServices method of the Startup class. You register your services and specify their lifetimes (e.g., Transient, Scoped, Singleton).

public void ConfigureServices(IServiceCollection services) { // Add your services to the DI container services.AddTransient<IMyService, MyService>(); }

Inject Dependencies:

In the classes where you want to use these dependencies, inject them via constructor injection or method injection.

Constructor Injection:

public class MyController : ControllerBase
{
    private readonly IMyService _myService;

    public MyController(IMyService myService)
    {
        _myService = myService;
    }

    // Use _myService in your methods
}

Method Injection:

public class MyController : ControllerBase { private readonly IMyService _myService; public MyController() { // Constructor with no parameters } // Method that accepts a dependency as a parameter public IActionResult MyAction([FromServices] IMyService myService) { // Use myService in your action } }

Use the Dependencies:

You can now use the injected dependencies within your class methods.

Optional: Automatically Inject Dependencies in Razor Pages and MVC Controllers:

If you're working with Razor Pages or MVC Controllers, .NET Core can automatically inject dependencies into controller actions without explicitly adding them to the constructor. You can use [FromServices] attribute to do this, as shown in the method injection example above.

Lifetime Management:

Choose an appropriate lifetime for your dependencies when registering them:

  • Transient: A new instance is created every time it's requested.
  • Scoped: A single instance is created per request.
  • Singleton: A single instance is created and shared across the application.
Dependency Injection simplifies the management of dependencies in your application, promotes testability, and helps you follow the SOLID principles. It's a core concept in modern .NET development and is widely used in ASP.NET Core applications.

Post a Comment

Previous Post Next Post