IServiceProvider is an interface with single method:
object GetService(Type serviceType);
It\'s used to create instances of ty
To get access to existing DI of ASP.NET Core application e.g. in some controller, you should register it in ConfigureServices method of Startup.cs:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton(services); // <- here
// ... other DI registrations
services.AddSingleton();
services.AddTransient();
}
After that, you can use it in any resolved objects from DI like this:
public class FooManager: IFooManager
{
private readonly ServiceProvider _di;
public FooManager(IServiceCollection serviceCollection)
{
_di = serviceCollection.BuildServiceProvider();
}
public void Start()
{
var w1 = _di.GetRequiredService(); // new instance of FooWorker
var w2 = _di.GetRequiredService(); // new instance of FooWorker
}
}