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