简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM