Skip to content

Instantly share code, notes, and snippets.

@antmdvs
Last active February 19, 2020 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antmdvs/867206f620d24fb282d409124577fc8f to your computer and use it in GitHub Desktop.
Save antmdvs/867206f620d24fb282d409124577fc8f to your computer and use it in GitHub Desktop.
HttpContext "Decoraptor" for ASP.NET MVC 5 - https://blog.ploeh.dk/2014/08/24/decoraptor/
public class FeatureAContextProvider : IFeatureContextProvider<FeatureAContext>
{
private readonly HttpContextBase _httpContext;
public FeatureAContextProvider(HttpContextBase httpContext)
{
// this would be a "decoraptor" (in quotes because it's wrapping ambient context 🤢)
_httpContext = httpContext;
}
public FeatureAContext GetContext()
{
return new FeatureAContext
{
Foo = _httpContext.Request.Headers["Foo"]
};
}
}
public class FeatureBContextProvider : IFeatureContextProvider<FeatureBContext>
{
private readonly IConfiguration _config;
public FeatureBContextProvider(IConfiguration config)
{
_config = config;
}
public FeatureBContext GetContext()
{
return new FeatureBContext
{
Bar = _config["Bar"]
};
}
}
public class HttpContextDecoraptor : HttpContextBase
{
private readonly Func<HttpContextBase> _httpContextFactory;
public HttpContextDecoraptor(Func<HttpContextBase> httpContextFactory)
{
_httpContextFactory = httpContextFactory;
}
public override HttpRequestBase Request => _httpContextFactory().Request;
/* ... remaining overrides ... */
}
var httpContextDecoraptor = new HttpContextDecoraptor(
httpContextFactory: () => new HttpContextWrapper(HttpContext.Current));
var featureAContextProvider = new FeatureAContextProvider(httpContextDecoraptor);
config.Filters.Add(new FeatureGateFilter(featureAContextProvider));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment