Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I see all services that a .NET IServiceProvider can provide?

Tags:

c#

.net

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?

like image 352
CamronBute Avatar asked Nov 26 '15 17:11

CamronBute


People also ask

How do I find my .NET core provider?

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.

Can you inject IServiceProvider?

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.


2 Answers

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/

like image 120
Adrian Hoffman Avatar answered Oct 24 '22 11:10

Adrian Hoffman


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.

like image 43
jBelanger Avatar answered Oct 24 '22 11:10

jBelanger