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