Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manual controller registration in ASP.NET Core dependency injection

I need to override ASP.NET Core's default registration for a certain controller.

I've tried the below, but it resolves MyController from the automatic registration.

services.AddTransient((provider) => new MyController(...));

How can I override this?

like image 293
Eric Eskildsen Avatar asked Aug 25 '19 15:08

Eric Eskildsen


1 Answers

By default, controllers are resolved using type activation, which boils down to the framework using an equivalent of Activator.CreateInstance to create controller instances. The dependencies for these controllers are sourced from the DI container, but the controller itself isn't.

Fortunately, there's a way to get the framework to use DI for the controllers too, using AddControllersAsServices. Here's an example (in ConfigureServices):

services.AddMvc().AddControllersAsServices();
like image 128
Kirk Larkin Avatar answered Oct 12 '22 08:10

Kirk Larkin