I have a scenario where I want to check a feature flag per request. The way I have implemented this so far is I use middleware..
public class SalesFeatureMiddleware
{
private readonly RequestDelegate _next;
private readonly IFeatureFlagRequestContext _featureFlagRequestContext;
public SalesFeatureMiddleware(
RequestDelegate next,
IFeatureFlagRequestContext featureFlagRequestContext)
{
_next = next;
_featureFlagRequestContext = featureFlagRequestContext;
}
public async Task InvokeAsync(HttpContext context)
{
var featureEnabled = _featureFlagRequestContext.GetValue("sale-flag");
context.Features.Set(SalesFeature.Create(featureEnabled));
await _next(context);
}
}
In my startup (ConfigureServices()), I use the following to inject this instance so I can use it later..
services.AddScoped(sp =>
{
var ctx = sp.GetRequiredService<IHttpContextAccessor>();
var feature = ctx.HttpContext.Features.Get<SalesFeature>();
return feature ?? SalesFeature.Default();
});
The idea is this is done once (per request), check status of the feature flag which can be changed during the running of the app as this is controlled using another service (Launch Darkly). I guess my question is, is this better suited to using a filter instead?