HomeNikola Knezevic

In this article

Banner

Feature Flags - Enable/Disable Features in .NET

24 Oct 2024
5 min

Sponsor Newsletter

Feature flags are a powerful tool for managing the development and deployment of new features.

They allow you to enable or disable specific features or parts of your code without redeploying the application. This makes it easy to control feature rollouts, limit visibility or address issues without the need for hotfixes or rollbacks.

Common Use Cases for Feature Flags:

  • Selectively enable or disable features for specific user segments.
  • Deactivate problematic features without the need for an emergency rollback.
  • Run experiments by releasing features to a small, controlled audience.
  • Deploy new features in production while limiting exposure to test their impact before full release.

Best of all, implementing feature flags in .NET is straightforward.

Getting Started with Feature Flags

To get started with Feature Flags, Microsoft has a native package that you can use.

You can do this via the NuGet Package Manager or by running the following command in the Package Manager Console:

bash
Install-Package Microsoft.FeatureManagement

After the package is installed, you need to register the service using AddFeatureManagement():

csharp
builder.Services.AddFeatureManagement();

This method adds feature management service and built-in feature filters.

By default, this method retrieves feature flags specified in the appsettings under the FeatureManagement configuration section.

However, you can specify a different section in this call if you prefer not to use the default one.

csharp
builder.Services.AddFeatureManagement(
    builder.Configuration.GetSection("FeatureFlags"));
appsettings.json
{
   "FeatureFlags": {
      "GetUserFlag": true,
      "UsersFlag": true,
      "GetOrderFlag": true
   }
}

In order to use feature flags you also need to define them in your codebase as well. Common approach is by creating an enum or by defining constants.

Here is an example of how I define them:

csharp
public static class FeatureFlags
{
    public const string GetUserFlag = nameof(GetUserFlag);
    
    public const string UsersFlag = nameof(UsersFlag);
    
    public const string GetOrderFlag = nameof(GetOrderFlag);
}

Basic Usage

Once everything is setup you can start checking feature flag states with IFeatureManager.

Here is an simple example using Minimal APIs:

csharp
// Checks if the feature flag is enabled using IFeatureManager
app.MapGet("orders", async (IFeatureManager featureManager) =>
{
    var isEnabled = await featureManager.IsEnabledAsync(FeatureFlags.GetOrderFlag);
    
    return isEnabled
        ? Results.Ok("Feature is enabled")
        : Results.Ok("Feature flag is not enabled");
});

In this simple example, depending on whether or not the feature is enabled, we will return an appropriate message.

If you are working with controllers and you wish to return 404 when the feature flag isn't enabled, then you don't need to inject the IFeatureManager necessarilly.

Rather you can utilize the FeatureGate attribute to apply feature flags on the controller or individual endpoint level.

csharp
// This controller is only active if the UsersFlag feature is enabled
[ApiController]
[Route("[controller]")]
[FeatureGate(FeatureFlags.UsersFlag)]
public class UsersController : ControllerBase
{
    // This endpoint is only active if the GetUserFlag feature is enabled
    [HttpGet]
    [FeatureGate(FeatureFlags.GetUserFlag)]
    public IActionResult Get()
    {
        return Ok("Feature is enabled");
    }
}

With this knowledge you are ready to implement your first feature flags.

More Complex Scenarios using Feature Filters

Feature filters allow you to control feature behavior based on complex conditions rather than simple on/off states.

.NET provides several built-in feature filters for quickly implementing common scenarios. In future blog posts I will also cover how to implement custom feature filters.

Here are some of the most commonly used built-in feature filters:

  • Percentage Filter: Enables you to gradually roll out a feature to a certain percentage.
  • TimeWindow Filter: Allows you to activate a feature during a specific time range. This one is especially interesting for time-sensitive features like promotions or events.
appsettings.json
{
   "FeatureFlags": {
      "GetUserFlag": {
         "EnabledFor": [
            {
               "Name": "Percentage",
               "Parameters": {
                  "Value": 75
               }
            }
         ]
      },
      "UsersFlag": {
         "EnabledFor": [
            {
               "Name": "TimeWindow",
               "Parameters": {
                  "Start": "22 Oct 2024 00:00:00 GMT",
                  "End": "23 Oct 2024 00:00:00 GMT"
               }
            }
         ]
      },
      "GetOrderFlag": true
   }
}

By leveraging feature filters, you gain fine-grained control over how and when features are enabled in your application.

Conclusion

Using feature flags allows you to deploy new features in production while controlling their availability. Essentially, they offer conditional logic to manage visibility or functionality during runtime.

Additionally they are especially useful in trunk-based development, where developers collaborate on a single branch. This helps minimize the risks of merging complex or large features, as flags can toggle functionality on or off, reducing the need for complex branch management.

If you want to check out examples I created, you can find the source code here:

Source Code

I hope you enjoyed it, subscribe and get a notification when new a blog is up!

Subscribe

Stay tuned for valuable insights every Thursday morning.