简体   繁体   中英

How to get the list of injected services to a controller

I need to get the list of all injected services of a specific type to a controller in an ASP.NET MVC 5 application. I am using Microsoft.Extensions.DependencyInjection as dependency injection container. I tried GetServices but it does not work.

serviceProvider.GetServices(typeof(IGenericRepository<,,>)).ToList()

serviceProvider is one of the services injected to the controller (IServiceProvider). As a test case, I can get one service using the following line of code (below), but I can't get the list of services.

IGenericRepository<CASES_BY_SUBTYPE, int, int> _CaseSubType = _serviceProvider.GetService<IGenericRepository<CASES_BY_SUBTYPE, int, int>>();

As far as I know, there is no build-in method could get all the service by using service provider, the GetServices method is just return a single service. If you still want to get all the services, you should build it by yourself.

I suggest you could refer to this answer to know how to build it. The replier get the codes from asp.net core unit test source codes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM