Previous Terraform All about JWT token Next

Dependency Injection in .NET Core

🧩 What is Dependency Injection?

Dependency Injection is a design pattern where an object receives its dependencies from an external source rather than creating them itself. In .NET Core, this is handled by a built-in IoC (Inversion of Control) container.

⚙️ How It Works in .NET Core

.NET Core uses a three-step process to implement Dependency Injection (DI):

1. Register Services

You register your services in the Startup.cs file (or Program.cs in .NET 6+), using the IServiceCollection interface.

services.AddTransient<IMyService, MyService>();
services.AddScoped<IMyService, MyService>();
services.AddSingleton<IMyService, MyService>();
  • Transient: A new instance is created every time it's requested.
  • Scoped: One instance per request.
  • Singleton: One instance for the entire application lifetime.

Comparison of Service Lifetimes in .NET Core

Method Lifetime Behavior Use Case
AddTransient Transient Creates a new instance every time it's requested. Lightweight, stateless services.
AddScoped Scoped Creates one instance per request. Services that maintain state during a single request.
AddSingleton Singleton Creates one instance for the entire application lifetime. Shared services or caches.

Example Registration

services.AddTransient<IMyService, MyService>();
services.AddScoped<IMyService, MyService>();
services.AddSingleton<IMyService, MyService>();
  

Injection Example

public class MyController : Controller
{
    private readonly IMyService _myService;

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

2. Build the Service Provider

.NET Core automatically builds the service provider when the application starts. This provider resolves dependencies when needed.

3. Inject Dependencies

You inject dependencies into constructors of controllers, services, or other classes:

public class MyController : Controller
{
    private readonly IMyService _myService;

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

.NET Core automatically provides the correct implementation based on what you registered.

🧪 Benefits of DI in .NET Core

  • Loose Coupling: Classes depend on abstractions, not concrete implementations.
  • Testability: Easier to mock dependencies for unit testing.
  • Maintainability: Centralized configuration of dependencies.

Tip

Constructor injection is the most common and recommended approach in .NET Core.

Back to Index
Previous Terraform All about JWT token Next
*