How to Impliment LaunchDarkly feature management in .net core api

3.6k Views Asked by At

I would like to add LaunchDarkly feature management in my .net core api.In a real time project how can i add this?

I have one interface file with all features.How will be this interface participate in LD call?

i am confused how to create a generic file for the configuration and call to different controllers! any help will be appreciated!

what I have did in my sample program..

  1. I created a flag in the LD website and added below code to main

    Configuration ldConfig = LaunchDarkly.Client.Configuration
                 // TODO: Enter your LaunchDarkly SDK key here
                 .Default("YOUR_SDK_KEY");
    
         LdClient client = new LdClient(ldConfig);
         User user = User.Builder("[email protected]")
           .FirstName("Bob")
           .LastName("Loblaw")
           .Custom("groups", "beta_testers")
           .Build();
    
         // TODO: Enter the key for your feature flag key here
         var value = client.BoolVariation("YOUR_FEATURE_FLAG_KEY", user, false);
    
         if (value)
         {
             Console.WriteLine("Showing feature for user " + user.Key);
         }
         else
         {
             Console.WriteLine("Not showing feature for user " + user.Key);
         }
    

But now i have a real time api project with huge lines of code, multiple controllers.How can i make this LD class generic? please help me..thanks

1

There are 1 best solutions below

0
On

First, declare the key in appsettings.json. Then create an interface class to declare the methods you want.

public interface IFeatureFlagsService
{
    T GetFeatureFlag<T>(string flagKey, string userKey);
}

Now implement this interface

using LaunchDarkly.Client;

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;
}
}

Make sure to inject configuration in startup.cs

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

Now you can inject this IFeatureFlagService in your controllers and call like

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