DI is a design pattern that allows classes to receive their dependencies from an external source, promoting loose coupling and testability. ASP.NET Core has built-in support for DI.
Lifetime Scopes:
- Transient: A new instance of the dependency is created every time it’s requested.
- Scoped: A new instance is created once per HTTP request.
- Singleton: A single instance is created and shared throughout the application’s lifetime.
public interface IMyService { string GetData(); }
public class MyService : IMyService { public string GetData() { return "Data from MyService"; } }
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IMyService, MyService>(); // Transient
// services.AddScoped<IMyService, MyService>(); // Scoped
// services.AddSingleton<IMyService, MyService>(); // Singleton
services.AddControllers();
}
public class MyController : ControllerBase
{
private readonly IMyService _myService;
public MyController(IMyService myService)
{
_myService = myService;
}
[HttpGet]
public string Get()
{
return _myService.GetData();
}
}
- The
ConfigureServices
method registers theIMyService
with the DI container. - The
MyController
constructor receives theIMyService
dependency.
Leave a Reply