Detailed configuration of Unity IOC injection (MVC, WebApi) and iocwebapi

Source: Internet
Author: User

Detailed configuration of Unity IOC injection (MVC, WebApi) and iocwebapi

I always wanted to write an article about the detailed configuration of unity.

First, we introduced unity. Unity is a lightweight IOC framework officially recommended by Microsoft. It supports various injection methods and is used as a powerful tool for decoupling.

You can directly download the corresponding dll file or download it from the corresponding website. I personally recommend using NuGet to directly add and manage it.

For example



After the installation, it will be automatically added to the project. When there is an Update, Update it directly in the window, or execute the command line Update-Package Mvc {tab}

If you only need to inject common MVC, you can do it now. However, if you still need to inject webapi, You need to introduce this library.

You can configure the package now,

In general, unity configuration is divided into three steps.

1: Fill in the specified ing relationship in the configuration file

2: Create a container to load the configuration file

3: Construct injection or property injection.

After completing these steps, you can start using them.


Let's talk about the configuration file first. First, let's look at the complete structure.

In fact, this is not the case if you are responsible for using it. If you just use it, you only need to pay attention to five 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 <alias> node is used to specify the ing relationship between the Assembly. alias indicates the node alias. type is used to specify the type. "The structure is namespace + file name, namespace ", <namespace> is used to specify the namespace property of the referenced assembly = namespace + folder name (if multiple mappings exist ), <assembly> name = "program namespace" is used to specify the referenced assembly.

<Container> is the container node. The <register> node in it uses the ing relationship between classes. type = "ing type", mapto =" ing target type" is marked with the corresponding code.

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(int i, int j)     {         var sum = ii.sum(i,j);         return sum * sum;     }    }}

After the configuration is complete. Registration is required.

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); // The injection method Bootstrapper. initialise ();}}}

Focus on Bootstrapper. Initialise (); Method

Using System; using System. collections. generic; using System. configuration; using System. linq; using System. web; using System. web. http; using System. web. mvc; using IservicesVc. test; using Microsoft. practices. unity; using Microsoft. practices. unity. configuration; using Services. test; using Unity. webApi; namespace TestUnityIocVC. app_Start {public static class Bootstrapper {public static void Initialise () {// Uni TyContainer container = new UnityContainer (); // UnityConfigurationSection configuration = ConfigurationManager. getSection (UnityConfigurationSection. sectionName) as UnityConfigurationSection; // configuration. configure (container, "defaultiner iner"); var container = BuildUnityContainer (); DependencyResolver. setResolver (new UnityDependencyResolver (container); // MVC injection // GlobalConfiguration. configurati On. 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 ;}}}

The BuildUnityContainer method is used to construct a container. The structure of the container is read from the configuration file. However, if you run the container, why is the error? If you need MVC injection, you still need to handle it.

We need to implement two new interfaces in MVC3: IDependencyResolver and IControllerActivator.

IDependencyResolver exposes two methods-GetServices. The GetService method of GetService solves The separate registration of services and supports creation of any object. GetServices registers multiple services. The implementation of the IDependencyResolver interface should be delegated to the underlying dependency injection container to provide the type of service request registration. When there is no registered service request type, the ASP. net mvc Framework expects the implementation of this interface to return GetService as null and return an empty set from GetServices. Let's use IDependencyResolver intreface to provide uniform dependency injection to create a custom dependency parser class.

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            {                return container.ResolveAll(serviceType);            }            catch            {                return new List<object>();            }        }    }}

Implement two methods: GetService and GetServices. Use the Unity container to return the required Service or ojbect.

Implement two methods: GetService and GetServices. Use the Unity container to return the required Service or ojbect.

ASP. net mvc 3 and later versions have launched a new interface IControllerActivator, allowing you to activate and customize the behavior controller, and can use dependency injection. let's create a custom controller derived from the IControllerActivator Interface


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

Here. The registration is complete.

Then it can be used in the MVC controller and webapi.


Using System; using System. collections. generic; using System. linq; using System. web; using System. web. mvc; using IservicesVc. test; using Microsoft. practices. unity; using Services. test; namespace TestUnityIocVC. controllers {public class HomeController: Controller {// property injection; [Dependency] public ITestIoc _ TestIoc {get; set;} public Itesttwo test = DependencyResolver. current. getService <Itesttwo> (); // private readonly ITestIoc _ testIoc; // public HomeController (ITestIoc testIoc) // {// _ testIoc = testIoc; //} public ActionResult Index () {var count = _ TestIoc. sum (10, 20); ViewBag. title = "home"; return View ();}}}


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(Itesttwo testIoc)        {            _testIoc = testIoc;        }        public IEnumerable<string> Get()        {            var sum = _testIoc.count(10, 20);            return new string[] { "value1", sum.ToString() };        }    }}

. Now the entire process is over. This is my first blog. Sorry for some inappropriate terms or unclear descriptions.

What are the advantages of dependency injection?

Let me express my views. I personally think that a large framework has nothing to do with reflection in a simple mechanism, but it only integrates many things. to achieve coordination, we still need a lot of research. therefore, simply speaking about the mechanism is nothing advanced. if we say coordination, it is not a perfect job for a person to do three days and two mornings. coordinates resources. it is important to coordinate user experience and coordinate data processing to the bottom layer of other software. such as databases. this is what I want to say. maybe not all, but I believe the landlord understands what I mean.

Related Article

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.