Dependency Injection (DI) is a fundamental concept in ASP.NET Core. It allows you to write loosely coupled, testable, and maintainable code by injecting the required dependencies into your classes instead of hard-coding them. ASP.NET Core has a built-in DI container that supports constructor injection and handles object lifetimes efficiently.
What is Dependency Injection?
Dependency Injection (DI) is a design pattern used to achieve Inversion of Control (IoC) between classes and their dependencies. Rather than a class creating its own dependencies, they are provided from outside, typically via the constructor.
📌 In simple terms: A class doesn’t create what it needs — it receives it from someone else.
Use of Dependency Injection:
- Promotes loose coupling
- Makes code testable
- Supports the separation of concerns
- Encourages interface-based programming
Step-by-Step Implementation of Dependency Injection:
dotnet new webapi -n MyApi cd MyApi
public interface IProductService { IEnumerable<string> GetProducts(); }
public class ProductService : IProductService { public IEnumerable<string> GetProducts() { return new List<string> { "Product1", "Product2", "Product3" }; } }
var builder = WebApplication.CreateBuilder(args); // Register the ProductService with the DI container builder.Services.AddScoped<IProductService, ProductService>(); var app = builder.Build();
using Microsoft.AspNetCore.Mvc; [ApiController] [Route("api/[controller]")] public class ProductsController : ControllerBase { private readonly IProductService _productService; // Constructor injection public ProductsController(IProductService productService) { _productService = productService; } [HttpGet] public IActionResult Get() { var products = _productService.GetProducts(); return Ok(products); } }
Service Lifetimes in ASP.NET Core.
- Singleton
- Scoped
- Transient
- The service is stateless and thread-safe
- You want to cache or reuse resources
- Examples: Logging, Configuration, In-memory cache
- You want to maintain state only during a single request
- You’re working with Entity Framework Core DbContext
- Service is lightweight and stateless
- You need fresh data or processing logic every time
builder.Services.AddSingleton<ISingletonService, MyService>(); builder.Services.AddScoped<IScopedService, MyService>(); builder.Services.AddTransient<ITransientService, MyService>();
var mockService = new Mock<IProductService>(); mockService.Setup(x => x.GetAll()).Returns(new[] { "Test Product" }); var controller = new ProductsController(mockService.Object); var result = controller.GetAll();
No comments:
Post a Comment