Skip to main content

Dependency Injection and Routing

Learn how to use feature flags with dependency injection and routing in ASP.NET Core.

Dependency Injection​

Services can be conditionally injected, or conditionally decorate existing services.

AddTransient / AddScoped​

services.AddTransientForFeature<ILinkService, GlobalLinkService>("GlobalLink");

Decorate​

The decorator pattern injects the existing implementation of a service into the constructor of the decorator service

services.AddScoped<ITaxService, LocalTaxService>();
services.DecorateForFeature<ITaxService, AvalaraTaxService>("Avalara");
info

Transient, scoped and middleware flags take effect immediately and don't require an application restart. They are usually preferred for this reason over singleton implementations, which live for the entire lifetime of the application.

Routing​

MVC Filters​

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<SomeMvcFilter>(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.

Conditional Middleware​

Middleware can be conditionally executed by the use of feature flags

app.UseMiddlewareForFeature<ReferralTrackingMiddleware>("ReferralTracking");

With the above call, the application adds a middleware component that only appears in the request pipeline if the feature ReferralTracking 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<T>();
});