在ASP.NET Core依赖项注入中手动注册控制器 [英] Manual controller registration in ASP.NET Core dependency injection

查看:499
本文介绍了在ASP.NET Core依赖项注入中手动注册控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为某个控制器重写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.

幸运的是,有一种方法可以使用

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依赖项注入中手动注册控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆