ASP — ASP.NET Dependency Injection
Register Services
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddSingleton<ICacheService, CacheService>();
builder.Services.AddTransient<IEmailService, EmailService>();
Service Lifetimes
| Lifetime | Description |
|---|---|
| Transient | New instance each request |
| Scoped | Once per request |
| Singleton | One instance forever |
Service Interface
public interface IUserService
{
User GetById(int id);
IEnumerable<User> GetAll();
}
public class UserService : IUserService
{
private readonly AppDbContext _context;
public UserService(AppDbContext context)
{
_context = context;
}
public User GetById(int id) => _context.Users.Find(id);
public IEnumerable<User> GetAll() => _context.Users.ToList();
}
Inject in Controller
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
private readonly IUserService _userService;
public UsersController(IUserService userService)
{
_userService = userService;
}
[HttpGet]
public IActionResult GetAll()
{
return Ok(_userService.GetAll());
}
}
Mini Practice
- Create service interface
- Implement service
- Register service
- Inject in controller
Up Next
Continue with ASP.NET Configuration — configuration.
Related Topics
Frequently Asked Questions about ASP.NET Dependency Injection
What is ASP.NET Dependency Injection in ASP?
ASP.NET Dependency Injection is a fundamental concept in ASP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn ASP.NET Dependency Injection?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn ASP.NET Dependency Injection.
Why is ASP.NET Dependency Injection important in ASP?
ASP.NET Dependency Injection is essential for ASP development. Understanding this concept will help you write better code and solve real-world problems more effectively.