1.环境:.netframework
2.基本使用逻辑:
基本使用分两步考虑:(1)控制器的注册 (2)业务类的注册
业务类注册基本操作:
在接口中定义一个标识接口,其他的接口都继承自这个接口,利用容器将继承和实现这个接口的类注册。
3.具体实现过程
(1)在MVC项目中安装Autofac.mvc程序包 即:Install-Package Autofac.MVC5
(2)在MVC项目Global.asax文件添加如下代码:其中Service为本例业务类命名空间 IServiceSupport为定义的标识接口
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
var builider = new ContainerBuilder();
builider.RegisterControllers(typeof(MvcApplication).Assembly)
.PropertiesAutowired();//把当前程序集中的Controller都注册
///获取所有相关类库的程序集 Load()参数就是要加载程序集名称
Assembly[] assemblies = new Assembly[] { Assembly.Load("Service") };
builider.RegisterAssemblyTypes(assemblies)
//进行类型过滤 type1..IsAssignableFrom(type2)表示type1类型是否可以指向type2类型的对象
//放到此处即 将继承和实现IServiceSupport接口的类注册 避免注册无关的类
//IServiceSupport接口定义在IService类库项目中接口中无任何定义 主要作用就用在此处
.Where(type => !type.IsAbstract && typeof(IServiceSupport).IsAssignableFrom(type))
.AsImplementedInterfaces()
.PropertiesAutowired();
var container = builider.Build();
//注册系统级别的 DependencyResolver 这样当MVC框架创建Controller等对象时都像Autofac要对象
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
4.如出现 未能加载文件或程序集“xxx”或它的某一个依赖项。系统找不到指定的文件。测试MVC项目没有添加对业务类项目或者接口项目的引用。
5.项目源码链接:https://pan.baidu.com/s/17nZJKMTIU5dG5xIMF49TbQ
提取码:9xom