webapi框架搭建系列博客
前言
c#的依賴注入框架有unity、autofac,兩個博主都用過,感覺unity比較簡單而autofac的功能相對更豐富(自然也更復雜一點),本篇將基於前幾篇已經創建好的webapi項目,引入autofac功能。
前面我們已經搭建好webapi,並用了owin技術。這篇的autofac也將基於這兩種技術進行開發。
步驟
引入包
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本身的用法。
autofac的用法可總結為三步:
1、創建container buildervar builder = new ContainerBuilder();
autofac怎么注冊組件可以參考官網:http://autofac.readthedocs.io/en/latest/register/registration.html
3、生成依賴注入容器(如果是webapi則將容器傳給webapi的DependencyResolver對象)
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
用於測試的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>();
測試結果如下:

