14

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?

0

2 Answers 2

18

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();
Sign up to request clarification or add additional context in comments.

2 Comments

If we are on ASP.NET 3+, I think the equivalent is services.AddControllersWithViews().AddControllersAsServices() or similar
@PatrickSzalapski Yeah, that's right. I think you can still use AddMvc, but those other methods are recommended in the docs, etc.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.