Feature toggles in .NET Core and Azure

Intro

Feature toggles is an mechanism which allows you to control features and manage them within your application. For instance if you want to disable some functionality you can to that by changing some part of configuration without redeployment, rebuild etc. In this post I will show you how to configure it in a few easy steps in .NET Core web application and Azure. At the end you will find repository with example code which you can test it on your own.

Prerequisites

For using FeatureManagement in .NET Core application you will need two NuGet packages which you can install with two below commands with dotnet cli:

dotnet add package Microsoft.Azure.AppConfiguration.AspNetCore
dotnet add package Microsoft.FeatureManagement.AspNetCore

The first package called Microsoft.Azure.AppConfiguration.AspNetCore will be necessary if you want to use Azure App Configuration. If you want to store all feature toggles (aka feature flags) f.g. in appsettings.json, you don’t have to install the first package and you should install only the second one called Microsoft.FeatureManagement.AspNetCore. And of course you have to have some .NET Core app where you will implement feature toggles mechanism 😉.

If you would like to manage the feature toggles from Azure, you have to create Azure App Configuration - it is special service which allows you to manage app settings and feature flags from one place. You can create instance of Azure App Configuration like the other services in Azure - try to find App Configuration in the Marketplace. Before you create App Configuration, check the pricing details. For test and learn purposes you will definitely need the free version, but maybe you will need standard licence in production app.

App configuration

If you installed the packages from the previous paragraph, you are ready to start your adventure with feature flags. I will focus only on WebAPI app, because this kind of apps I’m developing on my daily basis. If you want to expand your knowledge, I would like to invite you to the last section of article called Literature where you can find many useful sources.

Basic

For using FeatureManagement in your app you have to do two things:

  • in ConfigureServices method in Startup class you have to add FeatureManagement:
services.AddFeatureManagement();
  • in appsettings.json you have to add section called FeatureManagement
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "FeatureManagement": {
    "FeatureA": true,
    "FeatureB": true
  }
}

Of course you can set any names of feature flags, it’s only example. You can change name of section too by parameterization of AddFeatureManagement method.

services.AddFeatureManagement(options =>
{
    options.UseConfiguration(Configuration.GetSection("MyFeatureFlags"));
});

With Azure App Configuration

If you would like to use Azure App Configuration too, you have to prepare CreateHostBuilder method from Program class like below:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
            webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
                {
                    var settings = config.Build();
                    config.AddAzureAppConfiguration(options =>
                    {
                        options.Connect(settings["ConnectionStrings:AppConfig"])
                            .UseFeatureFlags();
                    });
                })
                .UseStartup<Startup>());

and add middleware in Configure method in Startup class:

app.UseAzureAppConfiguration();

As you can see above, there is necessary to set connection string to the App Configuration in app. I stored it in appsettings.json, but you have to remember not to commit it to the repository 😉. You can to store it in environment variable and so on.

Then you have to add some feature toggles in App Configuration. Go to your App Configuration section. In Operations part in menu on the left side you can find button called Feature manager.

Feature manager button

After clicking on this button you can find list of currently created flags with current states. You can switch state of flag in this place.

List of feature toggles

You can create new flag by clicking on button Add above the list.

Add new feature toggle

Usage

It is worth noting that you can store feature toggles configuration in both places for one application, so you can hold part of feature toggles configuration in appsettings.json file and the rest in App Configuration and use them in the same time. In Literature section you can find great and complex article about types of feature toggles and ways of managing them written by Pete Hodgson on Martin Fowler’s blog, so I can imagine that you would like to split your toggles configuration.

Enumeration

For easy access to feature toggles and avoiding typos, you can create enumeration of feature flags in code.

1
2
3
4
5
6
7
8
9
namespace FeatureTogglesInNETCore
{
    public enum MyFeatureFlags
    {
        FeatureA,
        FeatureB,
        FeatureC
    }
}

By example

Below you can find an example controller prepared for the explanation purposes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.FeatureManagement;
using Microsoft.FeatureManagement.Mvc;

namespace FeatureTogglesInNETCore.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class HomeController : Controller
    {
        private readonly IFeatureManager _featureManager;

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

        [HttpGet("FeatureA")]
        [FeatureGate(MyFeatureFlags.FeatureA)]
        public IActionResult GetA()
        {
            return Ok("Feature A works!");
        }

        [HttpGet("FeatureB")]
        public async Task<IActionResult> GetB()
        {
            if (await _featureManager.IsEnabledAsync(nameof(MyFeatureFlags.FeatureA)))
            {
                return Ok("Feature B is enabled");
            }

            return Ok("Feature B is NOT enabled");
        }

        [HttpGet("FeatureC")]
        [FeatureGate(MyFeatureFlags.FeatureC)]
        public IActionResult GetC()
        {
            return Ok("Feature C works");
        }
    }
}

Between lines 12th and 17th you can find injection of service which implement IFeatureManager interface. It is service which allows you to get state of feature toogle. How? An example you can see in lines 29 - 32th. Of course we can hide this strange if instruction in factory, strategy, decorator or whatever you what - this is not purpose of this article and it depends on context.

Changing state in appsettings file or in App Configuration in Azure will impact on the app behavior. When you will set FeatureA or FeatureC flags on false, then you will get HTTP404 error. I hope you noticed FeatureGate annotations in lines 20th and 38th. It allows to switch off controller method. You can add this annotation to controller’s class too, so when you will change state of toogle, you will switch on or switch off whole controller. When you change the state of FeatureB toggle, you will get an appropriate inscription depending on the state.

Switching toggles

You have to remember that thanks to use this mechanism, you don’t have to recompile code and rebuild the package or comment code, create many feature branches etc. You have full configuration in one place and you can simply switch on and off parts of application. If you change configuration in appsettings file, you have to restart application. When you will change toggle in App Configuration, toggles will reload automatically without restarting application - by default after 30 seconds. Of course here you have possibility of changing configuration configuration.

To sum up

I hope you saw that it’s really easy mechanism in implementation, but of course in usage it can be as easy as it is very difficult. Many depends on context, number of toggles, architecture of application and so on. In this article I wanted to show you technical part of implementation with Azure and .NET Core. I prepared example project which you can clone and test on your own. You can find it on my GitHub. Remember that if you want to test it with App Configuration, you have to set connection string to App Configuration in appsettings.json file.

Literature

Below you can find sources which can be helpful in exploration of feature toggles topic and on which the article is based on:

Newsletter

Thank you for visiting my website. I hope you enjoyed the content that I prepared and learned something valuable from it. If you want to be informed about my next entries or occasionally get a message with a collection of some interesting links, please subscribe to my newsletter. I will be extremely pleased if you do this and join my community!

  • By clicking button below you agree to send you news from my blog, about my products and services. Above data are stored in Mailchimp and I do not share them to anyone. More info you can find in privacy policy.

comments powered by Disqus