Most of the code examples below are by Nick Chapsas, his youtube video Dynamically enabling features with Feature Flags in .NET Core 3.1 was super helpful.
All the code snippets below are available at https://github.com/carlpaton/FeatureFlagDemo
In its simplest form, a
feature is some new behavior in your application. Having feature managment allows us to iteratively ship small changes to production which are essentially hidden / turned off. We can turn these on based on some predicate, its common to use a claim from the authenticated users JWT in the logic.
if `user-email` ends with `@gmail.com` then return true
.Net supports feature flags in the following namespaces
We use appsettings.json as a home for the config.
Custom Flag Implementation code example below for this configuration.
NewFeatureAFlag is on and
NewFeatureBFlag is off.
HappyHolidaysFlag is on only between given time windows.
Although .Net supports this out the box a percentage calculation should not really be the responsability of the application instance. If this was running in a cluster (so several nodes running in K8’s) it would make sense for the load balancer to make this decision.
- Create the configuration, here the flag is
BrowserFlagand the filter is
Parameters:AllowedBrowsers. The configuration can be anything and just needs to match
- Create the options file as Features/BrowserFeatureOptions.cs, this is not automagically resolved but needs to be done using the filters context.
- Create the the filter as Features/BrowserFeatureFilter.cs, the alias
BrowserFeatureFilterneeds to match the name in the appsettings.json configuration. The interface
IFeatureFiltercomes from the namespace
Microsoft.FeatureManagementand has a single method EvaluateAsync which will be called by the framework.
- Dependency injection
Add a default implementation for the
Microsoft.AspNetCore.Http.IHttpContextAccessor this is the
httpContextAccessor instance injected into the filter.
public void ConfigureServices(IServiceCollection services)
Finally resolve the feature managment services
- Validate the flag
Controller action result annotation
If the flag passes then the endpoint will be served else it will return 404 Not found.
Using tag helpers in the view
Using conditions in the view
@if (await FeatureManager.IsEnabledAsync("BrowserFlag"))