ASP.NET MVC中使用Autofac依赖注入
官网文档:MVC — Autofac 7.0.0 documentation
2024年02月26日在.net 4.8 framework 建立的MVC项目中测试通过
引入NUGET包:Autofac和Autofac.Mvc5
Global中加入以下代码:
//autofac注入
ContainerBuilder builder = new ContainerBuilder();
// Register your MVC controllers. (MvcApplication is the name of
// the class in Global.asax.)
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<DAL.StudentRepository>().As<DAL.IStudent>(); //这是自己写的接口及实现
//移除原本的mvc的容器,使用AutoFac的容器,将MVC的控制器对象实例交由autofac来创建
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
HomeController中的注入代码:
private readonly IStudent dal;
public HomeController(IStudent dal)
{
this.dal = dal;
}
然后就可以直接用接口里定义的方法了