-
Notifications
You must be signed in to change notification settings - Fork 52
关于netcore中Controller打标签注入问题
俞正东 edited this page May 26, 2023
·
9 revisions
需要把controller的实例的生成也转交给autofac才行
具体可以可以看下文档: https://autofaccn.readthedocs.io/en/latest/integration/aspnetcore.html
在netcore3.0以下关键代码是:
services.AddMvc().AddControllersAsServices(); builder.Populate(services);
//这行代码代表 controller的实例的创建交给autofac容器处理
services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
//这行代码代表 PageModel的实例的创建交给autofac容器处理 (pagemodel是razor的概念)
services.Replace(ServiceDescriptor.Transient<IPageModelActivatorProvider, ServiceBasedPageModelActivatorProvider>());
//除了上面那段代码以外,只能实现autofac去创建controller对象
// 但是必须得打【Compoment】标签注册到autofac容器才行,注意:每个controller都得打
[Component]
public class HomeController : Controller
{
}
但是要注意,如果用到拦截器或者PointCut切面功能,需要保证你的方法需要是public virtual (因为默认是根据类型是class去创建动态代理的,如果是interface的话是不需要的,具体原因可以参考拦截器那里有说明)