13

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.

Wessel Loth
  • 253
  • 3
  • 10
  • What you are looking for may be answered in http://stackoverflow.com/questions/36680933/discovering-generic-controllers-in-asp-net-core – hmnzr May 02 '17 at 14:01
  • Possible duplicate of [Discovering Generic Controllers in ASP.NET Core](http://stackoverflow.com/questions/36680933/discovering-generic-controllers-in-asp-net-core) – hmnzr May 02 '17 at 14:01

1 Answers1

17

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.

Ricardo Peres
  • 13,724
  • 5
  • 57
  • 74
  • I guess it can really be that simple! I assumed from reading the source code that this would not be possible, but that actually does the job I want. Thanks! – Wessel Loth May 02 '17 at 14:12
  • 1
    No problem! You probably would like to reuse the implementation in DefaultControllerFactory. If you do, add in your MyCustomControllerFactory the same parameters as DefaultControllerFactory and instantiate a private field of DefaultControllerFactory in your constructor using these parameters, so that you can delegate to it. – Ricardo Peres May 02 '17 at 14:14
  • I was just getting to that point of figuring out what the DefaultControllerFactory does under the bonnet, so this is a livesaver! Thanks! – Wessel Loth May 02 '17 at 14:18