Skip to content

Fix conditional registrations ignored when default has different reuse lifespan#697

Draft
Copilot wants to merge 4 commits into
masterfrom
copilot/fix-conditional-registrations
Draft

Fix conditional registrations ignored when default has different reuse lifespan#697
Copilot wants to merge 4 commits into
masterfrom
copilot/fix-conditional-registrations

Conversation

Copy link
Copy Markdown

Copilot AI commented Apr 8, 2026

When a conditional service (Setup.With(condition: ...)) and an unconditional fallback are registered for the same interface with different reuse lifespans, the conditional registration is bypassed — the fallback is always resolved, even when the condition matches.

container.Register<IService, MyServiceA>(
    reuse: Reuse.Transient,
    setup: Setup.With(condition: r => r.DirectParent.ServiceType == typeof(ServiceConsumerA))
);
container.Register<IService, MyServiceB>(reuse: Reuse.Singleton); // default fallback

// consumerA.Service was MyServiceB (wrong) — condition was ignored
var consumerA = container.Resolve<ServiceConsumerA>();
var consumerB = container.Resolve<ServiceConsumerB>();

Root Cause

In GetServiceFactoryOrDefault, the ImplicitCheckForReuseMatchingScope block calls FindFactoryWithTheMinReuseLifespanOrDefault across all condition-matched factories and returns early with the result. Since Singleton has a lower lifespan value than Transient, it was always winning — before the existing "prefer conditioned factories" logic (further down) had a chance to run.

Fix

  • src/DryIoc/Container.cs: Within the reuse-matching early-return block, check whether exactly one of the reuse-matched factories carries an explicit Setup.Condition. If so, prefer it over the factory selected purely by minimum lifespan. Using reuseMatchedFactories (not the broader set) ensures we don't promote a conditioned factory whose scope is incompatible with the current resolution context.

  • test/DryIoc.IssuesTests/GHIssue631_Conditional_registrations.cs: Enabled TestWithDefaultScopedToSingleton in Run() — it was previously commented out as a known-failing case.

Copilot AI linked an issue Apr 8, 2026 that may be closed by this pull request
Copilot AI changed the title [WIP] Fix issues with conditional registrations Fix conditional registrations ignored when default has different reuse lifespan Apr 8, 2026
Copilot AI requested a review from dadhi April 8, 2026 23:53
Copilot finished work on behalf of dadhi April 8, 2026 23:53
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.

Conditional registrations

2 participants