Asp.Net MVC 之 Autofac 初步使用3 整合web api

來源:互聯網
上載者:User

標籤:ado   arc   content   select   rom   index   使用   函數   類型   

今天我們試著在WebApi2實現autofac的注入,關於這方面也是看了幾位園友的分享省了不少時間,所以結合著前篇的demo再建立webapi進行...

demo3:  http://pan.baidu.com/s/1eSCAZtC

一樣開篇還是發下大概demo結構:

 

還是nuget安裝 Autofac 以及 Autofac ASP.NET MVC 5  Integration 、Autofac ASP.NET WEB API 2.2 Integration

 看到有園友說屬性注入存在安全隱患,官方的建議是使用建構函式注入。

特意找了一下相關的內容,不過不確定觀點是否正確,有明白的朋友麻煩可以告知下,我也好補充下讓更多朋友明白哈,在此感謝。

優缺點:

1. 屬性注入直白易懂,缺點是對於屬性可選的時候,很多個建構函式會顯得類很臃腫。

2. 構造注入是一種高內聚的體現,特別是針對有些屬性需要在對象在建立時候賦值,且後續不允許修改(不提供setter方法)。

不囉嗦了,主要還是貼下WebApi2的Global檔案,裡面主要關注關於mvc與webapi註冊的地兒(紅色部分)

 #region 自動注入            //建立autofac管理註冊類的容器執行個體            var builder = new ContainerBuilder();            HttpConfiguration config = GlobalConfiguration.Configuration;            Assembly[] assemblies = Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll").Select(Assembly.LoadFrom).ToArray();            //註冊所有實現了 IDependency 介面的類型            Type baseType = typeof(IDependency);            builder.RegisterAssemblyTypes(assemblies)                   .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)                   .AsSelf().AsImplementedInterfaces()                   .PropertiesAutowired().InstancePerLifetimeScope();            //註冊MVC類型            // builder.RegisterControllers(assemblies).PropertiesAutowired();            //註冊Api類型            builder.RegisterApiControllers(assemblies).PropertiesAutowired();            //builder.RegisterFilterProvider();            builder.RegisterWebApiFilterProvider(config);            var container = builder.Build();            //註冊api容器需要使用HttpConfiguration對象            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);            //註冊解析            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));            #endregion

新添加 TestController

[RoutePrefix("api/Test")]    public class TestController : ApiController    {        readonly IUserRepository repository;        //構造器注入        public TestController(IUserRepository repository)        {            this.repository = repository;        }        [HttpGet]        public HttpResponseMessage Index()        {            return MessageToJson.ToJson(repository.GetAll());        }    }

MessageToJson 只是把結果轉了一下json

  //需添加  System.Web.Extensions.dll  引用        public static HttpResponseMessage ToJson(Object obj)        {            String str;            if (obj is String || obj is Char)            {                str = obj.ToString();            }            else            {                var serializer = new JavaScriptSerializer();                str = serializer.Serialize(obj);            }            var result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };            return result;        }

最後來測試下結果:

訪問/api/Test/Index

Asp.Net MVC 之 Autofac 初步使用3 整合web api

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.