This is a general question regarding .NET
I am given an instance of the IServiceProvider interface, but I have little documentation as to what might be possible to get from it. How would I find out a list of all the services it might provide?
An instance of IServiceProvider itself can be obtained by calling a BuildServiceProvider method of an IServiceCollection . IServiceCollection is a parameter of ConfigureServices method in a Startup class. It seems to be magically called with an instance of IServiceCollection by the framework.
You can inject an instance of type IServiceProvider into any method of a class. You can also take advantage of the ApplicationServices property of the IApplicationBuilder interface and the RequestServices property of the HttpContext class to retrieve an IServiceProvider instance.
Because this is still one of the top suggestions from google:
There is now a nuget extension set that you can pull down from M$ that extends the service provider and exposes several useful endpoints, one of those is "GetServices" which returns an IEnumerable based on the type you provide
https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection.Abstractions/
There might be a simple solution if you are using Core Web Application. Here's what I ended up doing.
In Startup:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton(services);
}
This way you can inject the IServiceCollection to any class that needs it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With