ASP.NET Core - Overriding the default ControllerFactory

asp.net-core, asp.net-core-mvc, c#, dependency-injection

Solution

Register your own implementation in ConfigureServices, after calling AddMvc:

services.AddSingleton<IControllerFactory, MyCustomControllerFactory>();

This way it will get called whenever a controller is to be built.

For completeness the best way is to actually implement an IControllerActivator and register it, since the default controller factory is not public. It will use whatever implementation of IControllerActivator is registered to actually create the controller class.

Problem

I'm in a very specific situation where I'd like to override the default ASP.NET Core ControllerFactory. I'd like to do this because I want to be in full control of what type of controller I handle each request with. The scenario is: - Request comes in with a specific subdomain - Based on this subdomain, I want to resolve a Generic type controller in the factory For example: - `category.website.com` is called - We see it's of type `category` and will use the generic `HomeController<T>` , using DI to inject the category so the type is of `HomeController<Category>` - The `HomeController<Category>` will use some generic methods on type `Category` methods to render the homepage. If I'm led to believe this link, a factory of type `DefaultControllerFactory` is registered on startup of the application. This seems to not be overridable. Any idea how I would go by this? The most logical options for us is using the old ASP.NET MVC version which allows you to set your own ControllerFactory, but we'd lose features like being able to use `SpaServices` to prerender our Angular application.

Original source

Related problems