Search code examples
c#.netasp.net-coredependency-injection

.net 8 DI GetServices<object> not working


In one of my services I need to get all provided services. So I tried:

public ServiceConstructor(IServiceProvider serviceProvider) {
    _serviceProvider = serviceProvider;
    var allServices = _serviceProvider.GetServices<object>();

But I always get no services returned. If I ask for a specific service this one is returned, so there are registered services.

I even tried to inherit all my services from a single interface I am asking for instead of , but with no success.


Solution

  • I dont' thinks get all services is a good idea, but you could try this get type names from assembly first.

        [Route("api/[controller]")]
        [ApiController]
        public class ValuesController : ControllerBase
        {
    
            private readonly IServiceProvider serviceProvider;
    
            public ValuesController(IServiceProvider serviceProvider)
            {
    
                this.serviceProvider = serviceProvider;
            }
            [HttpGet]
            public void test()
            {
                
                var types = AppDomain.CurrentDomain.GetAssemblies()
                     .SelectMany(s => s.GetTypes())
                     .ToList();
                foreach(var type in types)
                {
                    try
                    {
                        var instance = serviceProvider.GetService(type);
                        if (instance != null)
                        {
                            Console.WriteLine(instance.ToString());
                        }
                    }
                    catch
                    {
    
                    }
                }
            }
        }
    

    Test
    enter image description here