Feature flags are a way of controlling the availability and behavior of features in your application without changing the code. They can help you with testing, experimentation, and gradual rollout of new functionality. Blazor is a framework for building interactive web UIs using C# and .NET. In this blog post, I will show you how to use feature flags in a Blazor application using a simple in-memory feature manager and a custom feature flag component.
Prerequisites
To follow this tutorial, you will need:
- A Blazor Server or WebAssembly project. You can use the default template or create your own.
- The Microsoft.Extensions.Configuration and Microsoft.Extensions.Configuration.Json NuGet packages. You can install them by using the Package Manager Console or the Manage NuGet Packages option in Visual Studio.
Step 1: Define feature flags in appsettings.json
The first step is to define some feature flags in appsettings.json. This is a JSON file that stores the configuration settings for your application. You can use it to store the names and values of your feature flags. To do this, follow these steps:
- In the Solution Explorer, right-click on the folder wwwroot and select Add > New Item.
- In the Add New Item window, select JSON File and name it appsettings.json. Click Add.
- In the appsettings.json file, add a new section called “FeatureManagement” and define your feature flags as key-value pairs. For example, you can define a feature flag called “Counter”
Your appsettings.json file should look something like this:
{
"FeatureManagement": {
"Counter": "true"
}
}
Step 2: Create a feature manager service
The next step is to create a feature manager service that will read the feature flag settings from appsettings.json and provide a method to check the feature flag state. To do this, follow these steps:
- In the Solution Explorer, right-click on your project and select Add > Class.
- Name the class FeatureManager.cs and replace the existing code with the following code:
using Microsoft.Extensions.Configuration;
using System.Threading.Tasks;
namespace FeatureFlagBlazorExample.Client.Helpers
{
public interface IFeatureManager
{
bool IsEnabled(string feature);
}
public class FeatureManager : IFeatureManager
{
private readonly IConfiguration _configuration;
public FeatureManager(IConfiguration configuration)
{
_configuration = configuration;
}
public bool IsEnabled(string feature)
{
if (!string.IsNullOrEmpty(feature))
{
return _configuration.GetValue<bool>($"FeatureManagement:{feature}");
}
return false;
}
}
}
This class implements the IFeatureManager interface, which defines a method called IsEnabledAsync that takes a feature name as a parameter and returns a boolean value indicating whether the feature is enabled or not. The class uses the IConfiguration service to access the appsettings.json file and read the feature flag settings.
- In the program.cs file, add the following line before the line that contains await builder.Build().RunAsync();
builder.Services.AddSingleton<IFeatureManager, FeatureManager>();
This will register the FeatureManager class as a singleton service that implements the IFeatureManager interface.
Step 3: Create a feature flag component
The final step is to create a feature flag component that will render its child content only if the feature flag with the given name is enabled. It will use the IFeatureManager service to check the feature flag state asynchronously. To do this, follow these steps:
- In the Solution Explorer, right-click on the Pages folder and select Add > Razor Component.
- Name the component FeatureFlag.razor and replace the existing code with the following code:
@using FeatureFlagBlazorExample.Client.Helpers;
@inject IFeatureManager FeatureManager
@if (featureIsEnabled)
{
@ChildContent
}
@code {
private bool featureIsEnabled = false;
[Parameter]
public RenderFragment ChildContent { get; set; }
[Parameter]
public string FlagName { get; set; }
protected override void OnInitialized()
{
Console.WriteLine(FlagName);
if (string.IsNullOrEmpty(FlagName))
return;
featureIsEnabled = FeatureManager.IsEnabled(FlagName);
Console.WriteLine(featureIsEnabled);
}
}
This component will render its child content only if the feature flag with the given name is enabled. It uses the IFeatureManager service to check the feature flag state asynchronously.
Step 4: Use feature flags in your Blazor components
Now you are ready to use feature flags in your Blazor components. This will allow you to show or hide features based on the feature flag settings in appsettings.json. To do this, follow these steps:
- In the Solution Explorer, open the Counter.razor component and wrap the content of the page within the FeatureFlag like so
@page "/counter"
<FeatureFlag FlagName="Counter">
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
</FeatureFlag>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
Run your Blazor application and navigate to the home page and the fetch data page. You should see the features appear or disappear based on the feature flag settings in appsettings.json. You can also change the feature flag settings in appsettings.json and refresh the app in the browser. If it doesn’t work, you might need to check whether you have hot reload enabled or check if you actualy saved the change in the appsettings.json.
You can find the code here HerraHak/FeatureFlagBlazorExample (github.com)
Happy Coding !