Trung BìnhC# iconC#

3 lifetime của Dependency Injection trong ASP.NET Core là gì và dùng khi nào?

ASP.NET Core hỗ trợ ba lifetime, lựa chọn theo đặc tính stateful của service.

  • Transient: instance mới mỗi lần resolve — stateless utilities, helper
  • Scoped: cùng instance trong một HTTP request — DbContext, UnitOfWork
  • Singleton: một instance duy nhất suốt đời app — logging, configuration, in-memory cache

Không bao giờ inject Scoped vào Singleton — gây "captive dependency" bug nghiêm trọng (xem #2775).

Xem toàn bộ C# cùng filter theo level & chủ đề con.

Mở danh sách C#