Skip to content

support variant service match mode#607

Open
zhiyuanliang-ms wants to merge 2 commits into
zhiyuanliang/keyed-vspfrom
zhiyuanliang/vs-attribute
Open

support variant service match mode#607
zhiyuanliang-ms wants to merge 2 commits into
zhiyuanliang/keyed-vspfrom
zhiyuanliang/vs-attribute

Conversation

@zhiyuanliang-ms
Copy link
Copy Markdown
Member

Why this PR?

A follow up PR for #606, trying to resolve #604

Today VariantServiceProvider<T> only selects an implementation based on the assigned variant name. This PR adds an alternative mode where the implementation is selected based on the feature flag's enabled status (true/false), useful when a feature has no variants (e.g. a simple toggle flag).

Introduce VariantServiceMatchMode enum which has Variant (default) and Status value.

Usage:

// Service implementations
[VariantServiceAlias(true)]
public class EnabledCalculator : ICalculator { /* ... */ }

[VariantServiceAlias(false)]
public class DisabledCalculator : ICalculator { /* ... */ }

// Registration (keyed for lazy instantiation)
services.AddKeyedSingleton<ICalculator, EnabledCalculator>(true);
services.AddKeyedSingleton<ICalculator, DisabledCalculator>(false);

// Or normal registration
// services.AddSingleton<ICalculator, EnabledCalculator>();
// services.AddSingleton<ICalculator, DisabledCalculator>();

services.AddFeatureManagement()
    .WithVariantService<ICalculator>("AdvancedMath", VariantServiceMatchMode.Status);

Note that the AddKeyed* family takes object? serviceKey, not just string.
image

string implementationName = ((VariantServiceAliasAttribute)Attribute.GetCustomAttribute(implementationType, typeof(VariantServiceAliasAttribute)))?.Alias;
if (_serviceProvider is IKeyedServiceProvider)
{
TService keyedService = _serviceProvider.GetKeyedService<TService>(enabled);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what if i want to register my feature services against other keys?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't test it. But my expectation is that you can register the same service multiple times using different keys,

Copy link
Copy Markdown

@Stepami Stepami May 28, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm trying to tell that if I want to use some key other than the feature status the variant sp won't get my impl as it doesn't know and can't know it.

The point is for VariantSp to be able to resolve my service not just with boolean key but any user-provided

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