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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With