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();
}
}