Leveraging Feature Flags in .NET with FeatureManagement-Dotnet and LaunchDarkly Feature Flags
Tags: featureflag, dotnetcore, launchdarkly, httpclientfactory
Published: 2024-02-25 15:37:21

In the dynamic world of software development, where change is constant and agility is key, feature flags have emerged as a powerful tool to manage the deployment and release of software features. Within the .NET ecosystem, Microsoft's FeatureManagement-Dotnet and LaunchDarkly library provides a robust solution for implementing feature flags, enabling developers to seamlessly integrate feature management into their applications. Also, we'll explore how to seamlessly integrate LaunchDarkly feature flags into .NET Core applications using the HttpClientFactory for efficient HTTP requests, along with registration and injection of the LaunchDarkly REST client.


**Understanding FeatureManagement-Dotnet**

FeatureManagement-Dotnet, an open-source library developed by Microsoft, simplifies the implementation of feature flags in .NET applications. It offers a versatile set of features and APIs to define, evaluate, and control feature flags, empowering developers to manage feature lifecycles with ease.

The library supports various feature flag strategies, including simple on/off toggles, time window-based activation, percentage rollout, and custom conditions based on context or user attributes. This flexibility allows developers to tailor feature flag behavior to specific use cases and requirements.

**Importance of Feature Flags in Continuous Delivery**
Continuous Delivery (CD) aims to automate the process of delivering software changes to production reliably and efficiently. Feature flags play a crucial role in achieving the goals of CD by decoupling deployment from release and enabling incremental, controlled feature rollouts.

By utilizing feature flags, development teams can:

- 
**Mitigate Risk**: Gradually introduce new features to subsets of users or environments, allowing for thorough testing and validation before full release.

- 
**Enable Experimentation**: Try out different versions of features by showing them to different groups of users. This helps gather data to make informed decisions and improve the product based on user preferences.

- 
**Facilitate Progressive Deployment**: Implement progressive deployment strategies such as canary releases or blue-green deployments, minimizing disruption and ensuring smooth transitions.

- 
**Provide Rollback and Recovery**: Quickly revert to previous states in case of issues or regressions by deactivating feature flags, ensuring minimal impact on users and business operations.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lm9so7huc4tgjn0vaam7.png)

**Utilizing Feature Flags in Microservices Architecture**

Microservices architecture decomposes complex systems into smaller, independently deployable services, offering scalability, resilience, and flexibility. FF seamlessly integrate into a microservices architecture, providing the following benefits:

**Service Isolation**: Each microservice can independently manage its feature flags, allowing teams to evolve and release features autonomously without impacting other services.

**Dynamic Configuration**: FF enables dynamic feature configuration based on environmental variables, user attributes, or external conditions, ensuring adaptability across microservices.

**Cross-Service Coordination**: FF facilitate feature coordination and versioning across microservices, ensuring consistency and compatibility in distributed systems.

**Centralized Management with IFeatureManager Interface**

Now, let's explore how the IFeatureManager interface in .NET simplifies the management of feature flags. Here's an example illustrating its usage:

```
// Registering IFeatureManager dependency
public void ConfigureServices(IServiceCollection services)
{
    // Other service configurations
    services.AddFeatureManagement();
}
```

```
// Injecting and using IFeatureManager in a Controller
public class MyController : ControllerBase
{
    private readonly IFeatureManager _featureManager;

    public MyController(IFeatureManager featureManager)
    {
        _featureManager = featureManager;
    }

    [HttpGet]
    public IActionResult MyAction()
    {
        if (_featureManager.IsEnabledAsync("MyFeature").Result)
        {
            // Execute feature-specific logic
            return Ok("Feature is enabled");
        }
        else
        {
            // Fallback to default behavior
            return Ok("Feature is disabled");
        }
    }
}

```
In this example, the IFeatureManager interface is registered as a dependency in the ConfigureServices method of the startup class. Then, it is injected into a controller where feature flag evaluation is performed based on the "MyFeature" flag.


## LaunchDarkly

**Understanding LaunchDarkly Feature Flags:**
LaunchDarkly feature flags empower developers to dynamically control the visibility and behaviour of features in their applications. By leveraging feature flags, developers can roll out new functionality gradually, target specific user segments, and monitor feature usage in real time.

**Integrating LaunchDarkly REST API with .NET Core Using HttpClientFactory:**

To integrate LaunchDarkly feature flags into a .NET Core application using the LaunchDarkly REST API and HttpClientFactory, follow these steps:

**Create LaunchDarkly REST Client**:

Begin by creating a LaunchDarkly REST client that interacts with the LaunchDarkly REST API. This client will encapsulate the logic for making HTTP requests to the LaunchDarkly API endpoints.

**Register HttpClient Using HttpClientFactory**:

Register an HttpClient instance with the HttpClientFactory in the ConfigureServices method of the Startup class. Configure the HttpClient with the base address and any default headers required for authentication.

**Inject LaunchDarkly REST Client**:

Use dependency injection to inject the LaunchDarkly REST client into the application services where it is needed. The HttpClientFactory will manage the lifecycle of the HttpClient instances, ensuring efficient reuse and disposal.

**Example Implementation:**

Below is an example implementation demonstrating how to integrate LaunchDarkly feature flags into a .NET Core application using HttpClientFactory and dependency injection:

```
using System.Net.Http;
using System.Threading.Tasks;

public class LaunchDarklyRestClient
{
    private readonly HttpClient _httpClient;
    private const string BaseUrl = "https://app.launchdarkly.com/api/v2";
    private readonly string _apiKey;

    public LaunchDarklyRestClient(HttpClient httpClient, string apiKey)
    {
        _httpClient = httpClient;
        _apiKey = apiKey;
        _httpClient.BaseAddress = new Uri(BaseUrl);
        _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
    }

    public async Task<bool> IsFeatureEnabled(string flagKey, string userKey)
    {
        var response = await _httpClient.GetAsync($"/flags/{flagKey}/evaluations?user={userKey}");
        response.EnsureSuccessStatusCode();
        var responseContent = await response.Content.ReadAsStringAsync();
        // Parse JSON response and extract flag variation value
        // Return true or false based on flag variation value
        return true;
    }
}

```

In the Startup.cs file:

```
public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient<LaunchDarklyRestClient>();
    services.AddTransient<LaunchDarklyRestClient>();
    // Other service registrations
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Middleware configuration
}

```

In the application service where LaunchDarklyRestClient is needed:

```
public class MyFeatureService
{
    private readonly LaunchDarklyRestClient _launchDarklyRestClient;

    public MyFeatureService(LaunchDarklyRestClient launchDarklyRestClient)
    {
        _launchDarklyRestClient = launchDarklyRestClient;
    }

    public async Task<bool> IsMyFeatureEnabled(string userKey)
    {
        return await _launchDarklyRestClient.IsFeatureEnabled("my-feature-flag", userKey);
    }
}

```

**Conclusion**:

In summary, integrating LaunchDarkly feature flags into .NET Core applications using the LaunchDarkly REST API and HttpClientFactory provides a flexible and efficient approach to control feature rollout and monitor flag usage. Leveraging Feature Flags through the IFeatureManager interface in .NET is essential for achieving Continuous Delivery and maximizing the benefits of microservices architecture. By enabling controlled rollouts, experimentation, and dynamic configuration, developers can deliver value with confidence, adaptability, and resilience, staying ahead in the evolving landscape of technology.