Search code examples
c#asp.net-coreasp.net-core-mvc

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?


Solution

  • 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();