c#的依賴注入框架有unity、autofac,兩個博主都用過,感受unity比較簡單而autofac的功能相對更豐富(天然也更復雜一點),本篇將基於前幾篇已經建立好的webapi項目,引入autofac功能。html
前面咱們已經搭建好webapi,並用了owin技術。這篇的autofac也將基於這兩種技術進行開發。web
步驟c#
引入包api
using System.Reflection; using Autofac; using Autofac.Integration.WebApi; using webapi.example; namespace webapi.AutoFac { public static class ContainerBuilerCommon { public static IContainer GetWebApiContainer() { var builder = new ContainerBuilder();
// 註冊webapi的全部控制器 builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// 註冊一個用於測試的組件。 builder.RegisterType<Chinese>().As<People>(); return builder.Build(); } } }
除了builder.RegisterApiControllers(Assembly.GetExecutingAssembly())是註冊webapi控制器,其它全部的代碼都是autofac自己的用法。app
autofac的用法可總結爲三步:框架
一、建立container buildervar builder = new ContainerBuilder(); 函數
autofac怎麼註冊組件能夠參考官網:http://autofac.readthedocs.io/en/latest/register/registration.htmlpost
三、生成依賴注入容器(若是是webapi則將容器傳給webapi的DependencyResolver對象) 測試
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);ui
用於測試的people接口和兩個接口的實現類以下
public interface People { string Language(); } public class Chinese : People { public string Language() { return "漢語"; } } public class American:People { public string Language() { return "english"; } }
owin管道配置
public class Startup { /// <summary> /// owin的http請求管道配置函數 /// </summary> /// <param name="app"></param> public void Configuration(IAppBuilder app) { #region 寫在前面的配置 // 獲取webapi的配置 var config = WebApiConfig.OwinWebApiConfiguration(new HttpConfiguration()); // 獲取webapi的依賴注入容器 var container = ContainerBuilerCommon.GetWebApiContainer(); // 配置webapi的依賴注入 config.DependencyResolver = new AutofacWebApiDependencyResolver(container); #endregion #region owin組件註冊(要注意順序) app.UseAutofacMiddleware(container);// 先註冊autofac組件,須要依賴注入功能的組件在此後註冊 app.UseAutofacWebApi(config);//註冊AutofacWebApi組件後再註冊WebApi組件 app.UseWebApi(config); #endregion }
WebApiConfig類代碼以下(非核心代碼)
using System.Web.Http; namespace webapi.Configs { /// <summary> /// webapi 配置類 /// </summary> public static class WebApiConfig { /// <summary> /// 返回webapi的httpconfiguration配置 /// 用於webapi應用於owin技術時使用 /// </summary> /// <returns></returns> public static HttpConfiguration OwinWebApiConfiguration(HttpConfiguration config) { config.MapHttpAttributeRoutes();//開啓屬性路由 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); return config; } } }
測試依賴注入是否正常
建立IOCTestController控制器
/// <summary> /// 本代碼用來測試依賴注入是否正常 /// </summary> namespace webapi.example { public class IOCTestController : ApiController { private People _people; public IOCTestController(People people) { _people = people; } public IHttpActionResult GetLanguage() { return Ok(_people.Language()); } } }
注意:控制器裏的_people沒有用new的方法去建立,而是交給了控制器的構造函數,而且控制器的建立已經配置成由autofac進行依賴注入,以下代碼
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
因此autofac會在建立IOCTestController時用Chinese代替接口people
builder.RegisterType<Chinese>().As<People>();
測試結果以下: