I want to inject a service based on the HTTP header value. So I have 2 classes - DbDataProvider and InMemDataProvider, both are implemented from IDataProvider. Whenever an API
You can achieve this in your DI config in Startup.cs
.
They key is services.AddHttpContextAccessor()
which allows you to get access to the HttpContext.
services.AddHttpContextAccessor();
services.AddScoped();
services.AddScoped();
services.AddScoped(ctx =>
{
var contextAccessor = ctx.GetService();
var httpContext = contextAccessor.HttpContext;
// Whatever the header is that you are looking for
if (httpContext.Request.Headers.TryGetValue("Synthetic", out var syth))
{
return ctx.GetService();
}
else
{
return ctx.GetService();
}
});