Search code examples
c#asp.netasp.net-mvcasp.net-corednx

Dynamic IoC controller resolving ASP.NET 5


I am trying to make a routing system similar to Mvc in which users create classes/controllers and HTTP requests get routed to them. I have all the basics down and it works for the most part by using reflection.

The problem happens when I try to IoC/Dependency Injection/Service Resolver. I want people to be able to create a controller that injects services (just like mvc) by just declaring what they need in the constructor and adding them to the IoC container. I am able to pass/use the System.IServiceProvider to call the GetService(Type) on the controller type i need. This does not work though unless I specifically add the controller type(s) to the IoC container. One does not need to do register a controller in Mvc for IoC so I am sure there is a workaround.

I have tried looking into using reflection to finding all the 'ControllerBase' child classes from the running assembly/appdomain and on startup adding those to the IServiceProvider/IServiceCollection? But it seems that the move to ASP.NET 5/Dnx core 5 seems to have changed how appdomains and assemblies work or are accessed. Any direction on how to accomplish this automatically without a user having to register every controller would be great. Also any info on how mvc does this would also be great.


Solution

  • Code for creating object instance with dependency injection:

    public void ConfigureServices(IServiceCollection services)
    {
        HomeController controller;
    
        var controllerFactory = Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateFactory(typeof(HomeController), Type.EmptyTypes);
        controller = (HomeController)controllerFactory(services.BuildServiceProvider(), null);
    }
    

    For creating types MVC use instance DefaultTypeActivatorCache. And it use static object ActivatorUtilities.