Unity IOC Injection Detail configuration (MVC,WEBAPI)

Source: Internet
Author: User

Always wanted to write an article about unity's detailed configuration information, which is self-summarizing.

First introduced unity, unity is Microsoft's official recommended use of the lightweight IOC framework, support a variety of ways to inject, use to decouple the weapon.

How do you get unity? You can directly download the corresponding DLL files or to the corresponding website download, I personally recommend using NuGet to add and manage directly.

Add methods such as

After the installation is automatically added to the project, when there is an update, directly in the window to update the line, or execute command line update-package Mvc{tab}

And if you just need to inject normal MVC, then now it's okay. But if you're going to need to inject webapi, then you need to introduce this library.

AX, the package is ready now to start configuring,

In general, Unity's configuration is divided into 3 steps

1: Fill in the configuration file to specify the mapping relationship

2: Create a container to load the configuration file

3: Construct injection or attribute injection.

With these steps, you can start using the

Let's say the configuration file. Send a picture to see the complete structure first

In fact, it is very responsible for the use of the words are not so, if you are simply to use the words only need to focus on 5 nodes

<?xml version= "1.0" encoding= "Utf-8"?><configuration>  <configSections>    <section Name = "Unity" type= "Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration "/>  </configSections>  <unity>            <alias Alias = "IClass" type= "iservicesvc.test, iservicesvc"/>    <alias alias= "MyClass" type= "services.test, Services"/ >        <namespace name= "iservicesvc.test"/>    <namespace name= "services.test"/>        <assembly Name= "Iservicesvc"/>    <assembly name= "Services"/>        <container>         <register type= " Itesttwo "mapto=" Testtwo "/>      <register type=" Itestioc "mapto=" Testio "/>    </container>  </unity></configuration>

From the top down. The first <alias> node is used to specify the mapping relationship between assemblies alias is the alias that represents the node, and type is the "struct namespace + file name, namespace" for the specified type,,<namespace> The namespace used to specify the reference assembly Name property = namespace + folder name (if multiple mappings), <assembly > Name= "program Namespace" is used to specify the referenced assembly

<container> is the container node. The <register> node inside is used to map the relationship between classes, type= "type needs to be mapped", mapto= the corresponding code under "target type of the map"

namespace iservicesvc.test{Public    interface ITESTIOC    {        int sum (int sumone, int sumtwo);}    } 
Using system;using system.collections.generic;using system.linq;using system.text;using  System.threading.tasks;namespace iservicesvc.test{Public interface itesttwo {int count (int i, int j);}} 
Using iservicesvc.test;namespace services.test{public    class testio:itestioc    {  public int sum (int sumone, int sumtwo)      {          return sumone + sumtwo;         }}}
Using system;using system.collections.generic;using system.linq;using system.text;using  System.threading.tasks;using iservicesvc.test;using microsoft.practices.unity;namespace  services.test{public class Testtwo:itesttwo {[Dependency] public ITESTIOC II {get, set;} public int count (in t i, int j) {var sum = ii.sum (i,j); return sum * sum;       }}} 

After the configuration is complete. It is necessary to start registering.

Using system;using system.collections.generic;using system.linq;using system.web;using  System.web.http;using system.web.mvc;using system.web.optimization;using system.web.routing;using  Testunityiocvc.app_start;namespace testunityiocvc{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); Injection method bootstrapper.initialise ();             }}}

The emphasis is on bootstrapper.initialise (); methods

UsingSystem;usingSystem.collections.generic;usingSystem.configuration;usingSystem.linq;usingSystem.web;usingSystem.web.http;usingSystem.web.mvc;usingIservicesvc.test;usingMicrosoft.practices.unity;usingMicrosoft.practices.unity.configuration;usingServices.test;usingUnity.webapi;namespacetestunityiocvc.app_start{public static ClassBootstrapper {public static voidInitialise () {//unitycontainer container = new UnityContainer ();//unityconfigurationsection configuration = Configurationmanager.getsection (Unityconfigurationsection.sectionname) as unityconfigurationsection; Configuration. Configure (Container, "Defaultcontainer"); var container = Buildunitycontainer (); Dependencyresolver.setresolver (new Unitydependencyresolver (container));//mvc Injection// GlobalConfiguration.Configuration.DependencyResolver = new Unitydependencyresolver (container);//mvc GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver (container);// WEBAPI Injection}///<summary>// Builds the Unity container. </summary>//<returns></returns> private static Iunitycontainer Buildunitycontainer () {var container = new UnityContainer ();//container. Registertype<inodebiz, nodebiz> (); var filemap = new Execonfigurationfilemap {execonfigfilename = HttpContext.Current.Server.MapPath ("~/unity.config" ) }; Configuration configuration = configurationmanager.openmappedexeconfiguration (Filemap, Configurationuserlevel.none); var unitysection = (unityconfigurationsection) configuration. GetSection ("Unity"); container. Loadconfiguration (unitysection); Container. REGISTERTYPE<ITESTIOC, testio> (); return container;       }}}

By using the Buildunitycontainer method to construct the container, the structure of the container is read from the configuration file, but now if you run it you will get an error, because if you need MVC injection, you need some other processing.

We want to implement the new two interfaces available in MVC3: Idependencyresolver and Icontrolleractivator

Idependencyresolver exposes two methods-GetService's Getservices.the GetService method solves a separate registered service, supports the creation of arbitrary objects, and getservices resolves the registration of multiple services. The implementation of the Idependencyresolver interface should be delegated to the underlying dependency injection container to provide the type of registration service request. When there is a type of service request that is not registered, the ASP. NET MVC framework expects the implementation of this interface to return GetService to null and return an empty collection from GetServices. Let's create a custom dependency parser class with the Idependencyresolver Intreface derivation, which provides a unified dependency injection effort.

We define a class named Unitydependencyresolver:

Using system;using system.collections.generic;using system.web.mvc;using Microsoft.Practices.Unity ; namespace testunityiocvc{public    class Unitydependencyresolver:idependencyresolver {Iunitycontainer Container Public unitydependencyresolver (Iunitycontainer container) {This.container = container;} public Object  GetService (Type servicetype) {Try {return container. Resolve (servicetype); } catch {return null;} public ienumerable<object> getservices (Type servicetype) {try {Retu RN container. ResolveAll (servicetype); } catch {return new list<object>();          }}}} 

Implement two methods GetService and GetServices. Use the Unity container to return the service or ojbect we need.

Implement two methods GetService and GetServices. Use the Unity container to return the service or ojbect we need.

The later version of ASP. 3 has introduced a new interface, Icontrolleractivator, that lets you activate a behavior controller with a custom, and can use dependency injection. Let's create a derivation from Icontrolleractivator A custom controller for the interface

IController

Using system;using system.web.mvc;namespace testunityiocvc{public    class  Customcontrolleractivator:icontrolleractivator    {        IController icontrolleractivator.create ( System.Web.Routing.RequestContext RequestContext,            Type controllertype)        {            return  Dependencyresolver.current                . GetService (Controllertype) as IController;      }}}

To this. The entire registration is complete.

Then you can use the MVC controller and the WEBAPI.

(MVC)

Using system;using system.collections.generic;using system.linq;using system.web;using  System.web.mvc;using iservicesvc;using iservicesvc.test;using microsoft.practices.unity;using  Services.test;namespace testunityiocvc.controllers{public class Homecontroller:controller {//attribute injection;  [Dependency] public itestioc _testioc {GET, set, public itesttwo test = Dependencyresolver.current.getservice<i Testtwo>();//private readonly itestioc _testioc;//public homecontroller (itestioc testioc)//{//_testIoc = Test Ioc; Public ActionResult Index () {var count = _testioc.sum (ten); Viewbag.title = "Home"; return View ();            }}} 

(WEBAPI)

Using system;using system.collections.generic;using system.linq;using system.net;using  System.net.http;using system.web.http;using iservicesvc.test;namespace TestUnityIocVC.Controllers.Api {public class Testcontroller:apicontroller {private readonly itesttwo _testioc, public TestController (Ite Sttwo testioc) {_testioc = testioc;} public ienumerable<string> Get () {var sum = _testioc.count (10, 20< c13>); return new string[] {"value1", Sum. ToString ()}; } }}

。 Well, it's the end of the whole process. This is my first time to write a blog. Please understand that some of the terms are inappropriate or not clearly described.

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.