4

I'm wanting to use Azure feature management to drive whether services are added to dependencies during startup .ConfigureServices(hostcontext, services =>

The only way I can find to do this is to call .BuildServiceProvider to get the IFeatureManagement.

var featureManager = services.BuildServiceProvider().GetRequiredService<IFeatureManager>();
if (featureManager.IsEnabledAsync(Features.MY_FEATURE).GetAwaiter().GetResult())
{
    services.AddFeatureDependencies();
}

There has got to be a better way to do this. Is there a service extension I'm missing somewhere? Something like below?

services.IfFeatureEnabled(Features.MY_FEATURE) {
    services.AddFeatureDependencies();
}

Or maybe by using the IConfiguration interface which can get other configuration values?

hostContext.Configuration.GetValue<bool>($"FeatureManager:{FeatureManagement.MY_FEATURE}");
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Ryan Langton
  • 6,294
  • 15
  • 53
  • 103
  • What's the need for determining whether to inject the dependencies or not, though? Will some unwanted side-effect happen just by injecting the services? Like, are you replacing some service? – Camilo Terevinto Nov 19 '21 at 14:22
  • If the service exists it is later started which has a startup performance impact.. scaled to 100s of workers it's significant and we don't want this to happen.. perhaps the logic really should move to where we're starting the service.... but the later example above (using configuration) does work – Ryan Langton Nov 19 '21 at 14:25
  • You're not going to be able to turn the feature flag on later if you don't inject the dependencies, so perhaps feature flagging this is not the best way. I'd personally just use a simple configuration like in the later example above. Also, depending on how this is deployed, it might make more sense to just add the feature flag as an environment variable as part of the build/release pipeline – Camilo Terevinto Nov 19 '21 at 14:28

1 Answers1

3

I found usefull to create extension method for this:

public static class ConfigurationExtensions
{
    public static bool IsFeatureEnabled(this IConfiguration configuration, string feature)
    {
        var featureServices = new ServiceCollection();
        featureServices.AddFeatureManagement(configuration);
        using var provider = featureServices.BuildServiceProvider();
        var manager = provider.GetRequiredService<IFeatureManager>();

        return manager.IsEnabledAsync(feature).GetAwaiter().GetResult();
    }
}
Jan Muncinsky
  • 4,282
  • 4
  • 22
  • 40