问题
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 call is made, a header is passed by the client which determines whether DbDataProvider is required or InMemDataProvider is required. How do I achieve that? So in short I need to inject service in the ServiceCollection in one of the middlewares. Is that possible?
The problem is that in the ConfigureService method in Startup class I cannot get the HttpContext. I have written a middleware using which I am able to get the HTTP Context but how do I inject a Service there?
回答1:
There is no easy or clean way to do this. You can't modify the IServiceCollection
outside of the ConfigureServices
method. But even if you could, it's of no use, because the container has already been built before Configure
is being called.
What you could do is create a factory class and register it as scoped.
public interface IDataProviderFactory
{
bool UseInMemoryProvider { get; set; }
IDataProvider Create();
}
public class DataProviderFactory : IDataProviderFactory
{
private readonly IServiceProvider provider;
public bool UseInMemoryProvider { get; set; }
public DataProviderFactory(IServiceProvider provider)
{
this.provider = provider;
}
public IDataProvider Create()
{
if(UseInMemoryProvider)
{
return provider.RequestService<InMemoryDataProvider>();
}
return provider.RequestService<DbDataProvider>();
}
}
Then in your middleware:
public class MyMiddleware
{
public void Invoke(HttpContext context)
{
var dataProviderFactory = context.RequestServices.RequestService<IDataProviderFactory>();
// Your logic here
if(...)
{
dataProviderFactory.UseInMemoryStore = true;
}
}
}
and in your controller/services:
public class MyController : Controller
{
private readonly IDataProvider dataProvider;
public MyController(IDataProviderFactory dataProviderFactory)
{
dataProvider = dataProviderFactory.Create();
}
}
回答2:
The answer above from Tsen is correct. You should implement a factory.
But in addition you can also register factory methods to the services collection. Like so:
Services.AddTransient(serviceProvider => serviceProvider.GetService<IDataProviderFactory>().Create())
This registers your IDataProvider. In the Create you should evaluate that HTTP header value so it returns the correct IDataProvider instance. Then in any class you need it you can simply request IDataProvider via the constructor and the correct implementation will be provided by the container.
回答3:
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<DbDataProvider>();
services.AddScoped<InMemDataProvider>();
services.AddScoped<IDataProvider>(ctx =>
{
var contextAccessor = ctx.GetService<IHttpContextAccessor>();
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<InMemDataProvider>();
}
else
{
return ctx.GetService<DbDataProvider>();
}
});
来源:https://stackoverflow.com/questions/38174474/injecting-service-in-middleware-in-asp-net-core