LaunchDarkly - How to add to IConfiguration - .NET 5.0

713 Views Asked by At

I've integrated LaucnhDarkly to my .NET 5 code using a FeatureFlagService class and using dependency injection like below.

services.AddSingleton<IFeatureFlagsService>(sp => new FeatureFlagsService(configuration));

And in the FeatureFlagsService.cs,

public class FeatureFlagsService : IFeatureFlagsService
{
    private readonly LdClient _ldClient;

    public FeatureFlagsService(IConfiguration configuration)
    {
        _ldClient = new LdClient(configuration["LaunchDarkly:Key"]);
    }

    public T GetFeatureFlag<T>(string flagKey, string userKey = "anonymous")
    {
        var user = User.WithKey(userKey);

        if (typeof(T).Equals(typeof(bool)))
            return (T)(object)_ldClient.BoolVariation(flagKey, user, default);
        else if (typeof(T).Equals(typeof(int)))
            return (T)(object)_ldClient.IntVariation(flagKey, user, default);
        else if (typeof(T).Equals(typeof(float)))
            return (T)(object)_ldClient.FloatVariation(flagKey, user, default);
        else if (typeof(T).Equals(typeof(string)))
            return (T)(object)_ldClient.StringVariation(flagKey, user, default);

        return default;
    }
}

And in any controller, I injected IFeatureFlagsService via constructor and used like below

_featureFlagService.GetFeatureFlag<bool>("externalUsersAllowed");

Now I would like to take out this featureflagservice.cs and add the LaunchDarkly to existing IConfiguration and use like

_configuation.GetValue<bool>("externalUsersAllowed")

How can I achieve this? Your help would be greatly appreciated.

1

There are 1 best solutions below

0
On

You'd need to implement a custom configuration provider by implementing IConfigurationSource in order to have access to them via the configuration object, IOptions, etc

This article provides examples for how to do so: https://learn.microsoft.com/en-us/dotnet/core/extensions/custom-configuration-provider