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