Manual controller registration in ASP.NET Core dependency injection

一世执手 提交于 2020-06-08 16:37:50

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/57647392/manual-controller-registration-in-asp-net-core-dependency-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!