autofac使用筆記

 

在以前的項目中用來解耦的使用的輕型IOC框架是unity,它的使用也是很方便的提供在以前的文章的也提到過它的使用方式,可是使用久了以後發現了它的不足之處就是須要配置xml文件來對應的接口和實現的關係。總覺這種不夠靈活。由於隨着項目的進行須要配置的接口和實現會愈來愈多。配置起來非常麻煩還容易出錯。我在想有沒有別的IOC框架可以一勞永逸的實現解耦而不是經過配置呢。web

答案是確定的。 那就是autofac ,這是我在Github 上找到的輕型的IOC框架。它的使用方式也特別的簡單。原理呢簡單來講。是經過遍歷程序集來實現的(PS:固然它也是支持經過配置文件來實現的這裏我就不詳細說了)。詳細的信息呢你們能夠輕易autofac 的官網下載源碼來看。網址是 http://autofac.org/  它的最大特點呢就是約定實現。什麼是約定實現。意思就是說你的接口和現實之間須要一個默認的約定。就跟建立控制器同樣必須以controller來結尾同樣。api

下面我就直接貼代碼了這個是我作的一個dome 是在在MVC5 webapi 中實現的注入mvc

 

固然在是用以前你須要在安裝幾個包。直接nuget就好了一共須要三個包框架

按順序說明下dom

step1 PM> Install-Package Autofac -Version 3.5.0 直接在包管理裏面輸入這個命令  nuget地址是https://www.nuget.org/packages/Autofac/3.5.0函數

 

step2 PM> Install-Package Autofac.Mvc5 添加這個包  nuget地址是https://www.nuget.org/packages/Autofac.Mvc5/ui

 

step3 PM> Install-Package Autofac.WebApi 最後是添加autofac webapi的包 https://www.nuget.org/packages/Autofac.WebApi/this

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;

namespace WebApiIoc.App_Start
{
    public static class autofaconfig
    {
        public static void Initialize(HttpConfiguration config)
        {
            Initialize(config, RegisterServices(new ContainerBuilder()));//初始化容器
        }

        public static void Initialize(HttpConfiguration config, IContainer container)
        {
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);//註冊api容器
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));//註冊MVC容器
        }

        private static IContainer RegisterServices(ContainerBuilder builder)
        {
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());//註冊api容器的實現

            builder.RegisterControllers(Assembly.GetExecutingAssembly());//註冊mvc容器的實現


            builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())//查找程序集中以services結尾的類型
                .Where(t => t.Name.EndsWith("Services"))
                .AsImplementedInterfaces();
            builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())//查找程序集中以Repository結尾的類型
           .Where(t => t.Name.EndsWith("Repository"))
           .AsImplementedInterfaces();

            return builder.Build();//返回容器
        }
    }
}

 這個是autofac的配置文件。spa

下面是webapiconfig文件code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using WebApiIoc.App_Start;

namespace WebApiIoc
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            //註冊webapi和mvc容器
            autofaconfig.Initialize(config);
        }
    }
}

最後是global文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using WebApiIoc.App_Start;

namespace WebApiIoc
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

        }
    }
}

在apicontroller和MVCcontroller裏面都是經過構造函數注入的方式實現的下面貼出來代碼

這個是MVC

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Iservices;
using Microsoft.Ajax.Utilities;

namespace WebApiIoc.Controllers
{
    public class HomeController : Controller
    {
        private IOneServices _oneServices;


        
        public HomeController(IOneServices oneServices)
        {
            _oneServices = oneServices;

        }

        public ActionResult Index()
        {
            var sum = _oneServices.sum(10, 20);


            var aa = DependencyResolver.Current.GetService<IOneServices>();

            ; ViewBag.Title = sum;

            return View();
        }
    }
}

這個是webapi

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Dependencies;
using Autofac;
using Autofac.Integration.WebApi;
using Iservices;

namespace WebApiIoc.Controllers
{
    public class ValuesController : ApiController
    {

        private IOneServices _oneServices;

        public ValuesController(IOneServices oneServices)
        
        {
            _oneServices = oneServices;

        }


        // GET api/values
        public IEnumerable<string> Get()
        {
            var sum = _oneServices.sum(1, 2);return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }
}

最後說明下若是你沒有經過構造函數注入你又想獲取實例的話怎麼作呢。下面分別說明

MVC

          var OneServices = DependencyResolver.Current.GetService<IOneServices>();

Webapi

            IDependencyScope dependencyScope = this.Request.GetDependencyScope();
            ILifetimeScope requestLifetimeScope = dependencyScope.GetRequestLifetimeScope();
            var customerService = requestLifetimeScope.Resolve<IOneServices>();

其餘的好比屬性注入和方法注入就不在這寫了。這裏只是寫的經常使用的簡單的註冊方式,後面我會把這部分註冊的方式給補上.

基本到這裏整個註冊流程就完事了。以上寫的不足之處請指出我會修正。但願和你們共同成長.

相關文章
相關標籤/搜索