问题描述
我需要为某个控制器重写ASP.NET Core的默认注册.
I need to override ASP.NET Core's default registration for a certain controller.
我已经尝试了以下方法,但是它可以从自动注册中解析MyController
.
I've tried the below, but it resolves MyController
from the automatic registration.
services.AddTransient((provider) => new MyController(...));
我该如何覆盖呢?
推荐答案
默认情况下,控制器使用类型激活进行解析,该激活使用等效的Activator.CreateInstance
归结到框架以创建控制器实例.这些控制器的依赖项来自DI容器,但控制器本身不是.
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.
幸运的是,有一种方法可以使用 AddControllersAsServices
.这是一个示例(在ConfigureServices
中):
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();
这篇关于在ASP.NET Core依赖项注入中手动注册控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!