AUTOFAC injection of ASP. NET Webapi and MVC

Source: Internet
Author: User

AUTOFAC has the advantages of decoupling, managing life cycle and so on, this paper only realizes a simple controller injection.

1. Create a new ASP. WEBAPI application (I'm using VS2013).

2. Download the following three packet through NuGet.

1   < PackageID= "AUTOFAC"version= "3.5.2"targetframework= "Net45" />2   < PackageID= "Autofac.mvc5"version= "3.3.3"targetframework= "Net45" />3   < PackageID= "Autofac.webapi2"version= "3.4.0"targetframework= "Net45" />

3. Create a new class management injection

     Public classContainerconfig { Public Static voidRegister (httpconfiguration config) {varBuilder =NewContainerbuilder (); Builder. Registerapicontrollers (assembly.getexecutingassembly ());//implementation of registering API containersBuilder. Registercontrollers (assembly.getexecutingassembly ());//implementation of registering an MVC container//injection of the ILog interfaceBuilder. Registertype<logone> (). As<ilog>(); Builder. Registertype<LogTwo> (). named<Object> ("Logtwo"). As<ilog>()///The Ilog type parameter named Logtwo is registered.            Named<t> This T does not know what the role, in here object, Logtwo and Ilog can be. IContainer Container=Builder.            Build (); Config. Dependencyresolver=NewAutofacwebapidependencyresolver (container);//Registering API containers requires the use of Httpconfiguration objectsDependencyresolver.setresolver (NewAutofacdependencyresolver (container));//Registering an MVC container        }    }

4. Call Containerconfig.register in Webapiconfig and pass in the parameters.

5, the above on the controller to inject custody. In the controller we can add the parameters we need.

     Public class Valuescontroller:apicontroller    {        public  Valuescontroller (ILog logtwo, ILog log)        {            if is  is Logone)            {            }        }    }

AUTOFAC injection of ASP. NET Webapi and MVC

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: info-contact@alibabacloud.com 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.