Choosing the right lifetime for your services is critical for app correctness and memory usage.
Transient
Created every time it is requested. Lightweight, stateless services.
Scoped
Created once per HTTP request. Ideal for DB contexts, user session data. Don’t inject Scoped into Singleton!
Singleton
Created once per application lifetime. Examples: Caching services, configuration. MUST be thread-safe.
services.AddTransient<IEmailSender, EmailSender>();
services.AddScoped<MyDbContext>();
services.AddSingleton<IMemoryCache, MemoryCache>();
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.