Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core - Overriding the default ControllerFactory

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:

  1. Request comes in with a specific subdomain
  2. Based on this subdomain, I want to resolve a Generic type controller in the factory

For example:

  1. category.website.com is called
  2. 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>
  3. 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.

like image 949
Wessel Loth Avatar asked May 02 '17 13:05

Wessel Loth


1 Answers

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.

like image 149
Ricardo Peres Avatar answered Nov 03 '22 03:11

Ricardo Peres