Using Unity for Dependency Injection in MVC 4

Source: Internet
Author: User

Using Unity for Dependency Injection in MVC 4

The concept of dependency injection is no longer described here, and we use MVC 4 in conjunction with unity, using constructors for dependency injection. The steps are as follows: 1. First build an MVC project and choose Basic

Once created, the complete project should look like this:

2. Create the home controller and add the index view

3. Create the UserInfo class, and the Iuser interface and the UserService class, UserService implement the method in the Iuser interface, where the business logic itself can be implemented according to the specific situation

4. Open the Nuget Program Management Pack, enter unity in the search box, and download the installation, as follows:

5. Create a dependency resolution container and implement two important methods in interface Idependencyresolver, Object GetService (Type servicetype) ienumerable<object> GetServices (Type servicetype) These two methods are the objects that return the service to which they are dependent

 <summary>//Dependency injection Resolver Container//</summary> public class Unityresolver        : idependencyresolver {protected Iunitycontainer container; Public unityresolver (Iunitycontainer container) {if (container = = null) {THR            ow new ArgumentNullException ("container");        } This.container = container; } public Object GetService (Type servicetype) {try {return CONTAINER.R            Esolve (servicetype);            } catch (resolutionfailedexception) {return null;                }} public ienumerable<object> getservices (Type servicetype) {try { Return container.            ResolveAll (servicetype);            } catch (Resolutionfailedexception) {return new list<object> (); }        }    }

6. Add a Unityconfig profile in App_start

Declare a static method with no return value in this file, Registercomponents, instantiate a parse container (also the parsing container you just added), and then register the interfaces and implementation classes that you depend on here. Container.  Registertype<iuserinfo, userinfoservice> (New Hierarchicallifetimemanager ()); Finally, call the Setresolver method of the Dependencyresolver object to save the registration.

public static void Registercomponents ()        {var container = new UnityContainer ();                        Register all your-the container here            //It's not necessary to register your controllers            //e.g . Container. Registertype<itestservice, testservice> ();                        Container. Registertype<iuserinfo, userinfoservice> (New Hierarchicallifetimemanager ());            Dependencyresolver.setresolver (new Unityresolver (container));                    }

7. Registering the Unityconfig profile in Global.cs

   Unityconfig.registercomponents ();

8. Using constructor injection in the home controller

      Iuserinfo Userinfoservice;      Public HomeController (Iuserinfo userinfoservice)      {        //Dependency Injection        this.userinfoservice = Userinfoservice;      }

Regenerate the project, if there is no error, start the run, we will see the kind of interface:

SOURCE download: Download source code

Using Unity for Dependency Injection in MVC 4

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.