-
Notifications
You must be signed in to change notification settings - Fork 0
Service Lifetimes
santiago edited this page Jan 29, 2026
·
1 revision
The framework supports three service lifetimes, each with different use cases and behaviors.
A single instance is created and reused throughout the application lifetime. Use for:
- Configuration objects
- Cached data
- Expensive-to-create services that don't need per-request state
# Simple registration
container.add_singleton(Configuration)
# Lambda registration
container.add_singleton(
IConfiguration,
lambda: Configuration(connection_string="...")
)A new instance is created per scope. In Azure Functions, a scope typically corresponds to:
- An HTTP request
- A function invocation
- A timer trigger execution
Use for:
- Services that need request-specific state
- Database contexts
- Services that should be disposed after the request
# Simple registration
container.add_scoped(UserService)
# Lambda registration
container.add_scoped(
IUserService,
lambda: UserService(container.get_service(IDatabaseContext))
)Important: Scoped services are automatically disposed when the scope ends. If your service implements IDisposable, the dispose() method will be called automatically.
A new instance is created every time the service is requested. Use for:
- Lightweight services
- Services that should never be shared
- Services with no state
# Simple registration
container.add_transient(EmailService)
# Lambda registration
container.add_transient(
IEmailService,
lambda: EmailService(container.get_service(IConfiguration))
)| Lifetime | When to Use | Instance Created |
|---|---|---|
| Singleton | Configuration, caches, shared state | Once per application |
| Scoped | Request-specific services, database contexts | Once per scope (request) |
| Transient | Lightweight, stateless services | Every time requested |
All three lifetimes support both simple and lambda registration:
# Singleton
container.add_singleton(ServiceClass)
container.add_singleton(IService, lambda: ServiceClass(...))
# Scoped
container.add_scoped(ServiceClass)
container.add_scoped(IService, lambda: ServiceClass(...))
# Transient
container.add_transient(ServiceClass)
container.add_transient(IService, lambda: ServiceClass(...))