Skip to content

feat(container): add conditional bindings - #70

Open
RomainLanz wants to merge 2 commits into
11.xfrom
feat/conditional-bindings
Open

feat(container): add conditional bindings#70
RomainLanz wants to merge 2 commits into
11.xfrom
feat/conditional-bindings

Conversation

@RomainLanz

Copy link
Copy Markdown
Member

Hey! 👋🏻

This PR adds a new API to register conditional bindings.

Example Story: You want to try a new payment gateway and roll-out that feature only to a few users.

With the new API, you can register a conditional bindings that resolve a different class depending on a condition.

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

container.bindWhen(
  PaymentGateway,
  async (resolver) => {
    const ctx = await resolver.make(HttpContext)
    return ctx.auth.user?.featureFlags.includes('new-payment') === true
  },
  (resolver) => resolver.make(BetaPaymentGateway)
)

RomainLanz and others added 2 commits August 15, 2026 11:48
Replaces "bindWhen" with a fluent builder, so conditional bindings read
like the rest of the container API and support singletons.

    container.if(condition).bind(PaymentGateway, resolver)
    container.if(condition).singleton(SearchService, resolver)

The "bindWhen" name collided with the existing "when" method used for
contextual bindings, where "when" refers to the parent class rather
than a predicate.

Changes:

- Extract the binding entry shape into "BindingEntry" and reuse it for
  conditional bindings, so both share a single resolution helper inside
  the resolver. Conditional bindings now get the same singleton caching
  and run-hooks-once behavior as regular bindings, instead of
  re-implementing hooks and events.

- Pass the parent asking for the binding to the condition as a third
  argument. Conditions can now combine a predicate with the calling
  class. The parent is null when resolving directly via "make".

- Attach a help message when a binding only has conditional bindings
  registered and none of their conditions match. Without it, the error
  reads like the binding was never registered.

- Make "conditionalBindings" optional on the ContainerResolver
  constructor, so constructing a resolver directly is not a breaking
  change.

- Document the full resolution order, the condition arguments, the need
  to guard conditions that read request specific values, and that
  "hasBinding" reports registration rather than resolvability.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants