Autofac usage notes

Source: Internet
Author: User

The lightweight IOC framework used for decoupling in previous projects is unity, which is also very convenient to use. It is also mentioned in previous articles, however, after a long time of use, I found that its shortcomings are the relationship between interfaces and implementations that need to be configured in the XML file. This is not flexible enough. As the project progresses, more interfaces and implementations need to be configured. Configuration is troublesome and error-prone. I was wondering if other IOC frameworks can achieve decoupling once and for all, instead of configuring them.

The answer is yes. That is autofac, which is a lightweight IOC framework I found on GitHub. It is also very simple to use. The principle is simple. It is implemented by traversing the Assembly (PS: Of course, it also supports implementation through the configuration file, which I will not elaborate on here ). For details, you can easily download the source code from the official autofac website. Web site is biggest characteristic is agreed to achieve. What is Convention implementation. This means that a default convention is required between your interface and the reality. Just like creating a controller, it must end with a controller.

I will directly paste the code below. This is a dome injection implemented in the mvc5 webapi.


Of course, you need to install several packages before using them. Just run nuget. A total of three packages are required.

Explain in order

Step 1 PM> install-package autofac-version 3.5.0 enter this command directly in package management nuget address is


Step 2 PM> install-package autofac. mvc5 add this package nuget address is


Step 3 PM> install-package autofac. webapi is finally the package for adding autofac webapi



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. 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 ())); // initialize container} public static void initialize (httpconfiguration config, icontainer container) {config. dependencyresolver = new autofacwebapidependencyresolver (container); // register the API container dependencyresolver. setresolver (New autofacdependencyresolver (container); // register the MVC container} Private Static icontainer registerservices (containerbuilder builder) {builder. registerapicontrollers (assembly. getexecutingassembly (); // register the API container implementation builder. registercontrollers (assembly. getexecutingassembly (); // register the implementation builder of the MVC container. registerassemblytypes (appdomain. currentdomain. getassemblies () // find the types ending with services in the Assembly. where (t => T. name. endswith ("services ")). asimplementedinterfaces (); builder. registerassemblytypes (appdomain. currentdomain. getassemblies () // find the type ending with repository in the Assembly. where (t => T. name. endswith ("repository ")). asimplementedinterfaces (); Return builder. build (); // return container }}}

This is the configuration file of autofac.

Below is the webapiconfig File

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}); // register webapi and MVC container autofaconfig. initialize (config );}}}

Finally, the Global File

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);        }    }}

The following code is implemented in both apicontroller and mvccontroller through constructor injection.

This is 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();        }    }}

This is 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)        {        }    }}

Finally, Let's explain how to get an instance if you didn't inject it through the constructor. The following describes


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


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

Others, such as property injection and method injection, are not written here. Here is just a common simple registration method. I will add this part of registration method later.

The registration process is complete. Note that I will correct the deficiencies mentioned above. Hope to grow together with everyone.

Autofac usage notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

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.