Eric Eskildsen
Eric Eskildsen

Reputation: 4769

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?

Upvotes: 14

Views: 7094

Answers (2)

Anatoliy Kostyuk
Anatoliy Kostyuk

Reputation: 76

one particular controller: ibuilder.Services.AddTransient<OldController, CustomOldController>();

Upvotes: 0

Kirk Larkin
Kirk Larkin

Reputation: 93153

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

Upvotes: 18

Related Questions