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
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();
}
return provider.RequestService();
}
}
Then in your middleware:
public class MyMiddleware
{
public void Invoke(HttpContext context)
{
var dataProviderFactory = context.RequestServices.RequestService();
// 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();
}
}