[英]Manual controller registration in ASP.NET Core dependency injection
I need to override ASP.NET Core's default registration for a certain controller.我需要为某个控制器覆盖 ASP.NET Core 的默认注册。
I've tried the below, but it resolves MyController
from the automatic registration.我已经尝试了以下方法,但它从自动注册中解析了MyController
。
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.默认情况下,控制器使用类型 activation解析,归结为框架使用等效的Activator.CreateInstance
来创建控制器实例。 The dependencies for these controllers are sourced from the DI container, but the controller itself isn't.这些控制器的依赖项来自 DI 容器,但控制器本身不是。
Fortunately, there's a way to get the framework to use DI for the controllers too, using AddControllersAsServices
.幸运的是,有一种方法可以让框架也使用 DI 用于控制器,使用AddControllersAsServices
。 Here's an example (in ConfigureServices
):这是一个示例(在ConfigureServices
):
services.AddMvc().AddControllersAsServices();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.