Microsoft.FeatureManagement provides standardized APIs for enabling feature flags within applications. Utilize this library to secure a consistent experience when developing applications that use patterns such as beta access, rollout, dark deployments, and more.
Feature flags provide a way for ASP.NET Core applications to turn features on or off dynamically. Developers can use feature flags in simple use cases like conditional statements to more advanced scenarios like conditionally adding routes or MVC filters. Feature flags build on top of the .NET Core configuration system. Any .NET Core configuration provider is capable of acting as the back-bone for feature flags.
Here are some of the benefits of using this library:
IConfiguration
API Reference: https://go.microsoft.com/fwlink/?linkid=2091700
Feature flags are composed of two parts, a name and a list of feature-filters that are used to turn the feature on.
Feature filters define a scenario for when a feature should be enabled. When a feature is evaluated for whether it is on or off, its list of feature-filters are traversed until one of the filters decides the feature should be enabled. At this point the feature is considered enabled and traversal through the feature filters stops. If no feature filter indicates that the feature should be enabled, then it will be considered disabled.
As an example, a Microsoft Edge browser feature filter could be designed. This feature filter would activate any features it is attached to as long as an HTTP request is coming from Microsoft Edge.
The .NET Core configuration system is used to determine the state of feature flags. The foundation of this system is
IConfiguration. Any provider for IConfiguration can be used as the feature state provider for the feature flag library. This enables scenarios ranging from appsettings.json to Azure App Configuration and more.
The feature management library supports appsettings.json as a feature flag source since it is a provider for .NET Core's IConfiguration system. Below we have an example of the format used to set up feature flags in a json file.
{ "Logging": { "LogLevel": { "Default": "Warning" } },// Define feature flags in a json file "FeatureManagement": { "FeatureT": { "EnabledFor": [ { "Name": "AlwaysOn" } ] }, "FeatureU": { "EnabledFor": [] }, "FeatureV": { "EnabledFor": [ { "Name": "TimeWindow", "Parameters": { "Start": "Wed, 01 May 2019 13:59:59 GMT", "End": "Mon, 01 July 2019 00:00:00 GMT" } } ] } }
}
The
FeatureManagementsection of the json document is used by convention to load feature flag settings. In the section above, we see that we have provided three different features. Features define their feature filters using the
EnabledForproperty. In the feature filters for
FeatureTwe see
AlwaysOn. This feature filter is built-in and if specified will always enable the feature. The
AlwaysOnfeature filter does not require any configuration so it only has the Name property.
FeatureUhas no filters in its
EnabledForproperty and thus will never be enabled. Any functionality that relies on this feature being enabled will not be accessible as long as the feature filters remain empty. However, as soon as a feature filter is added that enables the feature it can begin working.
FeatureVspecifies a feature filter named
TimeWindow. This is an example of a configurable feature filter. We can see in the example that the filter has a parameter's property. This is used to configure the filter. In this case, the start and end times for the feature to be active are configured.
The following snippet demonstrates an alternative way to define a feature that can be used for on/off features. ``` JavaScript { "Logging": { "LogLevel": { "Default": "Warning" } },
// Define feature flags in config file "FeatureManagement": { "FeatureT": true, // On feature "FeatureX": false // Off feature }
} ```
To make it easier to reference these feature flags in code, we recommend to define feature flag variables like below.
// Define feature flags in an enum public enum MyFeatureFlags { FeatureT, FeatureU, FeatureV }
Feature flags rely on .NET Core dependency injection. We can register the feature management services using standard conventions.
using Microsoft.FeatureManagement; using Microsoft.FeatureManagement.FeatureFilters;public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddFeatureManagement() .AddFeatureFilter() .AddFeatureFilter(); } }
This tells the feature manager to use the "FeatureManagement" section from the configuration for feature flag settings. It also registers two built-in feature filters named
PercentageFilterand
TimeWindowFilter. When filters are referenced in feature flag settings (appsettings.json) the Filter part of the type name can be omitted.
Advanced: The feature manager looks for feature definitions in a configuration section named "FeatureManagement". If the "FeatureManagement" section does not exist, it falls back to the root of the provided configuration.
The simplest use case for feature flags is to do a conditional check for whether a feature is enabled to take different paths in code. The uses cases grow from there as the feature flag API begins to offer extensions into ASP.NET Core.
The basic form of feature management is checking if a feature is enabled and then performing actions based on the result. This is done through the
IFeatureManager's
IsEnabledAsyncmethod.
… IFeatureManager featureManager; … if (await featureManager.IsEnabledAsync(nameof(MyFeatureFlags.FeatureU))) { // Do something }
When using the feature management library with MVC, the
IFeatureManagercan be obtained through dependency injection.
public class HomeController : Controller { private readonly IFeatureManager _featureManager;public HomeController(IFeatureManager featureManager) { _featureManager = featureManager; }
}
MVC controller and actions can require that a given feature, or one of any list of features, be enabled in order to execute. This can be done by using a
FeatureGateAttribute, which can be found in the
Microsoft.FeatureManagement.Mvcnamespace.
[FeatureGate(MyFeatureFlags.FeatureX)] public class HomeController : Controller { … }
The
HomeControllerabove is gated by "FeatureX". "FeatureX" must be enabled before any action the
HomeControllercontains can be executed.
[FeatureGate(MyFeatureFlags.FeatureY)] public IActionResult Index() { return View(); }
The
IndexMVC action above requires "FeatureY" to be enabled before it can execute.
When an MVC controller or action is blocked because none of the features it specifies are enabled, a registered
IDisabledFeaturesHandlerwill be invoked. By default, a minimalistic handler is registered which returns HTTP 404. This can be overridden using the
IFeatureManagementBuilderwhen registering feature flags.
public interface IDisabledFeaturesHandler { Task HandleDisabledFeature(IEnumerable features, ActionExecutingContext context); }
In MVC views
tags can be used to conditionally render content based on whether a feature is enabled or not.This can only be seen if 'FeatureX' is enabled.
The
tag requires a tag helper to work. This can be done by adding the feature management tag helper to the ViewImports.cshtml file.HTML+Razor @addTagHelper *, Microsoft.FeatureManagement.AspNetCore
MVC action filters can be set up to conditionally execute based on the state of a feature. This is done by registering MVC filters in a feature aware manner. The feature management pipeline supports async MVC Action filters, which implement
IAsyncActionFilter.
services.AddMvc(o => { o.Filters.AddForFeature(nameof(MyFeatureFlags.FeatureV)); });
The code above adds an MVC filter named
SomeMvcFilter. This filter is only triggered within the MVC pipeline if the feature it specifies, "FeatureV", is enabled.
The feature management library can be used to add application branches and middleware that execute conditionally based on feature state.
app.UseMiddlewareForFeature(nameof(MyFeatureFlags.FeatureU));
With the above call, the application adds a middleware component that only appears in the request pipeline if the feature "FeatureU" is enabled. If the feature is enabled/disabled during runtime, the middleware pipeline can be changed dynamically.
This builds off the more generic capability to branch the entire application based on a feature.
app.UseForFeature(featureName, appBuilder => { appBuilder.UseMiddleware(); });
Creating a feature filter provides a way to enable features based on criteria that you define. To implement a feature filter, the
IFeatureFilterinterface must be implemented.
IFeatureFilterhas a single method named
EvaluateAsync. When a feature specifies that it can be enabled for a feature filter, the
EvaluateAsyncmethod is called. If
EvaluateAsyncreturns
trueit means the feature should be enabled.
Feature filters are registered by the
IFeatureManagementBuilderwhen
AddFeatureManagementis called. These feature filters have access to the services that exist within the service collection that was used to add feature flags. Dependency injection can be used to retrieve these services.
Some feature filters require parameters to decide whether a feature should be turned on or not. For example a browser feature filter may turn on a feature for a certain set of browsers. It may be desired that Edge and Chrome browsers enable a feature, while Firefox does not. To do this a feature filter can be designed to expect parameters. These parameters would be specified in the feature configuration, and in code would be accessible via the
FeatureFilterEvaluationContextparameter of
IFeatureFilter.EvaluateAsync.
public class FeatureFilterEvaluationContext { ////// The name of the feature being evaluated. /// public string FeatureName { get; set; }/// <summary> /// The settings provided for the feature filter to use when evaluating whether the feature should be enabled. /// </summary> public IConfiguration Parameters { get; set; }
}
FeatureFilterEvaluationContexthas a property named
Parameters. These parameters represent a raw configuration that the feature filter can use to decide how to evaluate whether the feature should be enabled or not. To use the browser feature filter as an example once again, the filter could use
Parametersto extract a set of allowed browsers that would have been specified for the feature and then check if the request is being sent from one of those browsers.
[FilterAlias("Browser")] public class BrowserFilter : IFeatureFilter { … Removed for examplepublic Task<bool> EvaluateAsync(FeatureFilterEvaluationContext context) { BrowserFilterSettings settings = context.Parameters.Get<browserfiltersettings>() ?? new BrowserFilterSettings(); // // Here we would use the settings and see if the request was sent from any of BrowserFilterSettings.AllowedBrowsers }
}
When a feature filter is registered to be used for a feature flag, the alias used in configuration is the name of the feature filter type with the filter suffix, if any, removed. For example
MyCriteriaFilterwould be referred to as MyCriteria in configuration.
"MyFeature": { "EnabledFor": [ { "Name": "MyCriteria" } ] }
This can be overridden through the use of the
FilterAliasAttribute. A feature filter can be decorated with this attribute to declare the name that should be used in configuration to reference this feature filter within a feature flag.
If a feature is configured to be enabled for a specific feature filter and that feature filter hasn't been registered, then an exception will be thrown when the feature is evaluated. The exception can be disabled by using the feature management options.
services.Configure(options => { options.IgnoreMissingFeatureFilters = true; });
Feature filters can evaluate whether a feature should be enabled based off the properties of an HTTP Request. This is performed by inspecting the HTTP Context. A feature filter can get a reference to the HTTP Context by obtaining an
IHttpContextAccessorthrough dependency injection.
public class BrowserFilter : IFeatureFilter { private readonly IHttpContextAccessor _httpContextAccessor;public BrowserFilter(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor)); }
}
The
IHttpContextAccessormust be added to the dependency injection container on startup for it to be available. It can be registered in the
IServiceCollectionusing the following method.
public void ConfigureServices(IServiceCollection services) { … services.TryAddSingleton(); … }
In console applications there is no ambient context such as
HttpContextthat feature filters can acquire and utilize to check if a feature should be on or off. In this case, applications need to provide an object representing a context into the feature management system for use by feature filters. This is done by using
IFeatureManager.IsEnabledAsync(string featureName, TContext appContext). The appContext object that is provided to the feature manager can be used by feature filters to evaluate the state of a feature.
MyAppContext context = new MyAppContext { AccountId = current.Id; }if (await featureManager.IsEnabledAsync(feature, context)) { … }
Contextual feature filters implement the
IContextualFeatureFilterinterface. These special feature filters can take advantage of the context that is passed in when
IFeatureManager.IsEnabledAsyncis called. The
TContexttype parameter in
IContextualFeatureFilterdescribes what context type the filter is capable of handling. This allows the developer of a contextual feature filter to describe what is required of those who wish to utilize it. Since every type is a descendant of object, a filter that implements
IContextualFeatureFiltercan be called for any provided context. To illustrate an example of a more specific contextual feature filter, consider a feature that is enabled if an account is in a configured list of enabled accounts.
public interface IAccountContext { string AccountId { get; set; } }[FilterAlias("AccountId")] class AccountIdFilter : IContextualFeatureFilter { public Task EvaluateAsync(FeatureFilterEvaluationContext featureEvaluationContext, IAccountContext accountId) { // // Evaluate if the feature should be on with the help of the provided IAccountContext } }
We can see that the
AccountIdFilterrequires an object that implements
IAccountContextto be provided to be able to evalute the state of a feature. When using this feature filter, the caller needs to make sure that the passed in object implements
IAccountContext.
Note: Only a single feature filter interface can be implemented by a single type. Trying to add a feature filter that implements more than a single feature filter interface will result in an
ArgumentException.
There a few feature filters that come with the
Microsoft.FeatureManagementpackage. These feature filters are not added automatically, but can be referenced and registered as soon as the package is registered.
Each of the built-in feature filters have their own parameters. Here is the list of feature filters along with examples.
This filter provides the capability to enable a feature based on a set percentage.
"EnhancedPipeline": { "EnabledFor": [ { "Name": "Microsoft.Percentage", "Parameters": { "Value": 50 } } ] }
This filter provides the capability to enable a feature based on a time window. If only
Endis specified, the feature will be considered on until that time. If only start is specified, the feature will be considered on at all points after that time.
"EnhancedPipeline": { "EnabledFor": [ { "Name": "Microsoft.TimeWindow", "Parameters": { "Start": "Wed, 01 May 2019 13:59:59 GMT", "End": "Mon, 01 July 2019 00:00:00 GMT" } } ] }
This filter provides the capability to enable a feature for a target audience. An in-depth explanation of targeting is explained in the targeting section below. The filter parameters include an audience object which describes users, groups, and a default percentage of the user base that should have access to the feature. Each group object that is listed in the target audience must also specify what percentage of the group's members should have access. If a user is specified in the users section directly, or if the user is in the included percentage of any of the group rollouts, or if the user falls into the default rollout percentage then that user will have the feature enabled.
"EnhancedPipeline": { "EnabledFor": [ { "Name": "Microsoft.Targeting", "Parameters": { "Audience": { "Users": [ "Jeff", "Alicia" ], "Groups": [ { "Name": "Ring0", "RolloutPercentage": 100 }, { "Name": "Ring1", "RolloutPercentage": 50 } ], "DefaultRolloutPercentage": 20 } } } ] }
All of the built-in feature filter alias' are in the 'Microsoft' feature filter namespace. This is to prevent conflicts with other feature filters that may share the same simple alias. The segments of a feature filter namespace are split by the '.' character. A feature filter can be referenced by its fully qualified alias such as 'Microsoft.Percentage' or by the last segment which in the case of 'Microsoft.Percentage' is 'Percentage'.
Targeting is a feature management strategy that enables developers to progressively roll out new features to their user base. The strategy is built on the concept of targeting a set of users known as the target audience. An audience is made up of specific users, groups, and a designated percentage of the entire user base. The groups that are included in the audience can be broken down further into percentages of their total members.
The following steps demonstrate an example of a progressive rollout for a new 'Beta' feature:
This strategy for rolling out a feature is built in to the library through the included Microsoft.Targeting feature filter.
An example web application that uses the targeting feature filter is available in the FeatureFlagDemo example project.
To begin using the
TargetingFilterin an application it must be added to the application's service collection just as any other feature filter. Unlike other built in filters, the
TargetingFilterrelies on another service to be added to the application's service collection. That service is an
ITargetingContextAccessor.
The implementation type used for the
ITargetingContextAccessorservice must be implemented by the application that is using the targeting filter. Here is an example setting up feature management in a web application to use the
TargetingFilterwith an implementation of
ITargetingContextAccessorcalled
HttpContextTargetingContextAccessor.
services.AddSingleton();services.AddFeatureManagement(); .AddFeatureFilter();
To use the
TargetingFilterin a web application an implementation of
ITargetingContextAccessoris required. This is because when a targeting evaluation is being performed information such as what user is currently being evaluated is needed. This information is known as the targeting context. Different web applications may extract this information from different places. Some common examples of where an application may pull the targeting context are the request's HTTP context or a database.
An example that extracts targeting context information from the application's HTTP context is included in the FeatureFlagDemo example project. This method relies on the use of
IHttpContextAccessorwhich is discussed here.
The targeting filter relies on a targeting context to evaluate whether a feature should be turned on. This targeting context contains information such as what user is currently being evaluated, and what groups the user in. In console applications there is typically no ambient context available to flow this information in to the targeting filter, thus it must be passed directly when
FeatureManager.IsEnabledAsyncis called. This is supported through the use of the
ContextualTargetingFilter. Applications that need to float the targeting context into the feature manager should use this instead of the
TargetingFilter.
services.AddFeatureManagement() .AddFeatureFilter();
Since
ContextualTargetingFilteris an
IContextualTargetingFilter, an implementation of
ITargetingContextmust be passed in to
IFeatureManager.IsEnabledAsyncfor it to be able to evaluate and turn a feature on.
IFeatureManager fm; … // userId and groups defined somewhere earlier in application TargetingContext targetingContext = new TargetingContext { UserId = userId, Groups = groups; }await fm.IsEnabledAsync(featureName, targetingContext);
The
ContextualTargetingFilterstill uses the feature filter alias Microsoft.Targeting, so the configuration for this filter is consistent with what is mentioned in that section.
An example that uses the
ContextualTargetingFilterin a console application is available in the TargetingConsoleApp example project.
Options are available to customize how targeting evaluation is performed across all features. These options can be configured when setting up feature management.
services.Configure(options => { options.IgnoreCase = true; });
Feature state is provided by the IConfiguration system. Any caching and dynamic updating is expected to be handled by configuration providers. The feature manager asks IConfiguration for the latest value of a feature's state whenever a feature is checked to be enabled.
There are scenarios which require the state of a feature to remain consistent during the lifetime of a request. The values returned from the standard
IFeatureManagermay change if the
IConfigurationsource which it is pulling from is updated during the request. This can be prevented by using
IFeatureManagerSnapshot.
IFeatureManagerSnapshotcan be retrieved in the same manner as
IFeatureManager.
IFeatureManagerSnapshotimplements the interface of
IFeatureManager, but it caches the first evaluated state of a feature during a request and will return the same state of a feature during its lifetime.
Implementing a custom feature provider enable developers to pull feature flags from sources such as a database or a feature management service. The included feature provider that is used by default pulls feature flags from .NET Core's configuration system. This allows for features to be defined in an appsettings.json file or in configuration providers like Azure App Configuration. This behavior can be substituted to provide complete control of where feature definitions are read from.
To customize the loading of feature definitions, one must implement the
IFeatureDefinitionProviderinterface.
public interface IFeatureDefinitionProvider { Task GetFeatureDefinitionAsync(string featureName);IAsyncEnumerable<featuredefinition> GetAllFeatureDefinitionsAsync();
}
To use an implementation of
IFeatureDefinitionProviderit must be added into the service collection before adding feature management. The following example adds an implementation of
IFeatureDefinitionProvidernamed
InMemoryFeatureDefinitionProvider.
services.AddSingleton() .AddFeatureManagement()
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.