據說.net 世界里,最強的依賴注入容器是Autofac 。不管是誰,Nopcommerce2.8 用了它,所以就簡單研究一下嘍。
用vs 2012 創建一個Asp.net mvc3 的樣例項目。然后使用NuGet(Vs2012 自帶的有,版本低的話,似乎要安裝插件),下載安裝autofac的dll,如圖1,2.
圖1 NuGet
圖2 ,load autofac
autofac 要加載兩個dll哦,一個是autofac 的core ,另外一個是和asp.net mvc3集成的dll
然后,我新建一個實體數據模型,鏈接我的數據庫,加載Customer這個我已經建好的表,字段隨意,數據隨意。實體類Customer自動生成。加一個集合類,裝customer,
public class LCust { public List<Customer> clist; }
接下來是一個ICusotmer接口和一個它的實現CustomerService:
public interface ICustomer { List<Customer>GetCustomers( ); } public class CustomerService : ICustomer { public List<Customer>GetCustomers() { return new SeendioEntities().T_Adv_Customer.ToList(); } }
好,准備工作就緒,開始依賴注入了。
在Gloabal.ascx文件中:
using Autofac; using Autofac.Builder; using Autofac.Integration.Mvc;
下面是編輯Application_Start()方法,對ICustomer進行依賴注入:
var builder = new ContainerBuilder(); builder.RegisterType<CustomerService>().As<ICustomer>();
在HomeController.cs中,修改構造函數:
private ICustomer _icustomer; public HomeController(ICustomer customerservice) { _icustomer = customerservice; }
修改action:
public ActionResult Index( ) { ViewBag.Message = "歡迎使用 ASP.NET MVC!"; List<Customer> clist = _icustomer.GetCustomers();//調用借口方法,獲取所有的Customer LCust c = new LCust(); c.clist = clist; return View(c); //把Customer返回給視圖 }
在index.cshtml 中顯示Customer列表中每一個customer的email:
@model MvcApplication2.LCust @{ ViewBag.Title = "主頁"; } <ul> @foreach (var item in Model.clist) { <li>@item.Email</li> } </ul>
運行,發現報了錯:
解決這個問題的方法似乎不少,我翻了翻Nopcommerce 2.8的代碼,發現了這么一個方法:RegisterControllers
於是在Application_Start()方法加上一句,對Controller進行依賴注入
builder.RegisterControllers(Assembly.GetExecutingAssembly());
問題解決,運行出結果。
Autofac 粗淺的用還簡單,但是在Nopcommerce2.8里,我看到了對它進行封裝的代碼,好糾結。
autofac實現依賴注入的方法有哪些,注入對象的生命周期等等,繼續分析,下次再會啊。