Skip to content

Service Lifetimes

santiago edited this page Jan 29, 2026 · 1 revision

Service Lifetimes

The framework supports three service lifetimes, each with different use cases and behaviors.

Singleton

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="...")
)

Scoped

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.

Transient

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))
)

Choosing the Right Lifetime

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 Lifetimes Support Both Registration Methods

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(...))

Related Topics

Clone this wiki locally