Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NETCORE use feature flags inside ConfigureServices

I'm using Feature Flags as described here. It works alright, I'm just wondering if the following is really the best way to use them if I want to switch between different service implementations inside ConfigureServices()?

I have the following so far:

using Microsoft.FeatureManagement;

public void ConfigureServices(IServiceCollection services)
{
    services.AddFeatureManagement();

    var sp = services.BuildServiceProvider();
    var featureManager = sp.GetService<IFeatureManager>();

    if (featureManager.IsEnabledAsync("UseServiceB").Result)
    {
        services.AddHostedService<MyServiceB>();
    }
    else
    {
        services.AddHostedService<MyServiceA>();
    }
}

Especially since IFeatureManager only provides an async method to check for a feature, this doesn't feel quite right?!

like image 218
silent Avatar asked Dec 05 '25 03:12

silent


1 Answers

I don't see any better way. 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();
    }
}
like image 80
Jan Muncinsky Avatar answered Dec 08 '25 04:12

Jan Muncinsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!