Skip to content

Conditional container bindings

Latest

Choose a tag to compare

@github-actions github-actions released this 24 Aug 07:21
Immutable release. Only release title and notes can be modified.

You can now select a container binding dynamically at resolution time using the new container.if API.

Conditions may be synchronous or asynchronous and have access to the current resolver, making conditional bindings especially useful for feature flags, per-request implementations, multi-tenancy, or environment-specific services.

container.bind(PaymentGateway, (resolver) => {
  return resolver.make(StripePaymentGateway)
})

container
  .if(async (resolver) => {
    const ctx = await resolver.make(HttpContext)

    return ctx.auth.user?.featureFlags.includes('new-payment') === true
  })
  .bind(PaymentGateway, (resolver) => {
    return resolver.make(BetaPaymentGateway)
  })

Multiple conditional bindings can be registered for the same key. They are evaluated in registration order, and the first matching binding is used. When no condition matches, the container falls back to the regular binding.

Conditional singletons are supported as well:

container
  .if(() => env.get('SEARCH_DRIVER') === 'typesense')
  .singleton(SearchService, (resolver) => {
    return resolver.make(TypesenseSearchService)
  })

The condition is evaluated on every resolution, while the singleton factory result remains cached.