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?!
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With