Unity 2.x Dependency Injection (inversion of control) IOC, these are unfamiliar nouns for children's shoes without major project experience, and even some of the students are stuck in the pull control stage.
You can access http://unity.codeplex.com/releases to get the latest version of Unity now. Of course, if you have the NuGet Package Manager installed in your Visual Studio, you can get the latest version of unity directly from NuGet. It looks like the latest is 3, and the 5th tells us the bad code shows how the interface
Here http://unity.codeplex.com/documentation we found a help document that you can download to see
We are using constructor injection, runtime injection.
This concept can be counted as the most obscure of the system, we should be well understood, blog Park a prawn
"ASP. MVC3" using unity to implement dependency injection let's go inside.
I'm not talking about it here anymore.
Put out the code and tell everyone how to do it.
Download Http://files.cnblogs.com/ymnets/Microsoft.Practices.Unity.rar
In the app.admin to create the library to put in, and later we will use the class libraries are put here, unless it is stated that the referenced class library is open source.
App.core references Microsoft.Practices.Unity.dll, SYSTEM.WEB.MVC, system.web,3 class library and 4. Bll,app.ibll,app.dal,app.idal 4 Classes of libraries
Add the following 2 classes
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingAPP.BLL;usingApp.dal;usingAPP.IBLL;usingApp.idal;usingMicrosoft.Practices.Unity;namespaceapp.core{ Public classDependencyregistertype {//System Injection Public Static voidContainer_sys (refUnityContainer Container) {container. Registertype<ISYSSAMPLEBLL, syssamplebll> ();//Sample ExampleContainer. Registertype<isyssamplerepository, syssamplerepository>(); } }}
Using system;using system.collections.generic;using system.web;using system.web.mvc;using Microsoft.Practices.Unity ; namespace app.core{public class Unitydependencyresolver:idependencyresolver {Private Const string HTTPCO Ntextkey = "Perrequestcontainer"; Private ReadOnly Iunitycontainer _container; Public unitydependencyresolver (Iunitycontainer container) {_container = container; public Object GetService (Type servicetype) {if (typeof (IController). IsAssignableFrom (servicetype)) {return childcontainer.resolve (servicetype); } return isregistered (servicetype)? childContainer.Resolve (servicetype): null; } public ienumerable<object> getservices (Type servicetype) {if (isregistered (servicetype)) {yield return childcontainer.resolve (servicetype); } foreach (Var seRvice in Childcontainer.resolveall (servicetype)) {yield return service; }} protected Iunitycontainer Childcontainer {get {var Childco Ntainer = Httpcontext.current.items[httpcontextkey] as Iunitycontainer; if (Childcontainer = = null) {Httpcontext.current.items[httpcontextkey] = Childcontainer = _container. Createchildcontainer (); } return childcontainer; }} public static void Disposeofchildcontainer () {var childcontainer = Httpcontex T.current.items[httpcontextkey] as Iunitycontainer; if (childcontainer! = null) {childcontainer.dispose (); }} private bool Isregistered (Type typetocheck) {var isregistered = true; if (Typetocheck.isinterface | | typetocheck.isabstract) {isregistered = childcontainer.isregistered (Typetocheck); if (!isregistered && typetocheck.isgenerictype) {var opengenerictype = Typetoch Eck. GetGenericTypeDefinition (); isregistered = childcontainer.isregistered (Opengenerictype); }} return isregistered; }}}unitydependencyresolver.cs
We inject the constructor as the system starts to run. So we're going to write the code in the global file
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 app.core;using Microsoft.practices.unity;namespace app.admin{//NOTE: For instructions on enabling IIS6 or IIS7 Classic mode,//please visit http://go.microsoft.com/? linkid=9394801 public class MvcApplication:System.Web.HttpApplication {protected void Application_Start () {Arearegistration.registerallareas (); Webapiconfig.register (globalconfiguration.configuration); Filterconfig.registerglobalfilters (globalfilters.filters); Routeconfig.registerroutes (routetable.routes); Enable compression bundletable.enableoptimizations = true; Bundleconfig.registerbundles (Bundletable.bundles); Authconfig.registerauth (); Inject Ioc var container = new UnityContainer (); Dependencyregistertype.container_sys (ref Container); Dependencyresolver.setresolver (new Unitydependencyresolver (container)); }}}global.asax.cs
Well, we've put
ISYSSAMPLEBLL, SYSSAMPLEBLL
Isyssamplerepository, Syssamplerepository
injected into the system.
Since the EF-generated entity model has a transactional state, we have always wanted to minimize the overhead, and we want to reconstruct the Syssample class
In App.models new Folder Sys, if not specifically stated, SYS represents the system, a areas area corresponds to a file, and the area we will use later
App.models To reference the System.ComponentModel.DataAnnotations class library
Using system;using system.componentmodel.dataannotations;using System.runtime.serialization;namespace app.models.sys{public class Syssamplemodel { [Display (Name = ' id ')] public string ID {get; set;} [Display (name = "names")] public string Name {get; set;} [Display (Name = "age")] [Range (0,10000)] public int? Age {get; set;} [Display (Name = "Birthday")] Public DateTime? Bir {get; set;} [Display (Name = "Photo")] public string Photo {get; set;} [Display (Name = "Introduction")] public string Note {get; set;} [Display (Name = "Creation Time")] Public DateTime? createtime {get; set;}}}
Why are we doing this? It's not already syssample, why do we have to Syssamplemodel
- We should take care of the distributed Web services of the future system, the BLL layer distribution
- We should not still be in the controller still operating the bottom, should be converted to
In the future, we will appreciate the benefits. You can take it here.
Next we re-write the Ibll,bll,controller code, Dal,idal code is no problem, very focused on the bottom
BLL Reference Microsoft.Practices.Unity Class Library
The modified code
Using system.collections.generic;using app.models.sys;namespace app.ibll{public interface ISYSSAMPLEBLL {// /<summary>//Get list///</summary>/<param name= "pager" >jqgrid pagination </param> <param name= "Querystr" > Search conditions </param>//<returns> list </returns> List<sys Samplemodel> GetList (String querystr); <summary>///Create an entity///</summary>//<param name= "errors" > Persistent error message </param& Gt <param name= "model" > Model </param>//<returns> Success </returns> bool Create (syssample Model model); <summary>///delete an entity///</summary>//<param name= "errors" > Persistent error message </param& Gt <param name= "id" >id</param>///<returns> successful </returns> bool Delete (string ID); <summary>//Modify an entity </summary>//<param name= "errors" > Persistent error message </param>//<param name= "model" > modulo Type </param>///<returns> successful </returns> bool Edit (Syssamplemodel model); <summary>///The model entity is obtained by ID///</summary>//<param name= "id" >id</param& Gt <returns>model entities </returns> Syssamplemodel GetById (string id); <summary>///Determine if there are entities///</summary>//<param name= "id" > Primary key id</param> Whether <returns> exists </returns> bool Isexist (string ID); }}isyssamplebll.cs
Using system;using system.collections.generic;using system.linq;using microsoft.practices.unity;using App.Models; Using app.common;using app.models.sys;using app.ibll;using app.idal;namespace app.bll{public class Syssamplebll:isys SAMPLEBLL {Dbcontainer db = new Dbcontainer (); [Dependency] public isyssamplerepository Rep {get; set;} <summary>///Get a list//</summary>//<param name= "pager" >jqgrid pagination </param> ; <param name= "Querystr" > Search conditions </param>//<returns> list </returns> public List<sys Samplemodel> GetList (String querystr) {iqueryable<syssample> querydata = null; Querydata = rep.getlist (db); return Createmodellist (ref querydata); } private list<syssamplemodel> Createmodellist (ref iqueryable<syssample> Querydata) { List<sysSamplemodel> modellist = (from R in Querydata select New Syssamplemodel {Id = R.id, Name = r.name, age = R.age, Bir = R.bir, Photo = R.photo, Note = r.note, Createtime = r.c Reatetime,}). ToList (); return modellist; }///<summary>//Create an entity///</summary>//<param name= "errors" > Persistent error message &L t;/param>//<param name= "model" > Models </param>//<returns> success </returns> p ublic bool Create (Syssamplemodel model) {try {syssample entity = Rep.getbyid (model. ID); if (Entity! = NULL) {return false; } entity = new Syssample (); Entity. Id = model. Id; Entity. Name = model. Name; Entity. Age = Model. Age; Entity. Bir = model. Bir; Entity. Photo = model. Photo; Entity. Note = model. Note; Entity. Createtime = model. Createtime; if (rep.create (entity) = = 1) {return true; } else {return false; }} catch (Exception ex) {//exceptionhander.writeexception (ex); return false; }}///<summary>//Delete an entity///</summary>//<param name= "Errors" >Persistent error message </param>//<param name= "id" >id</param>//<returns> Success </returns> public bool Delete (string id) {try {if (rep.delete (id) = = 1) {return true; } else {return false; }} catch (Exception ex) {return false; }}///<summary>//Modify an entity///</summary>//<param name= "errors" & gt; Persistent error messages </param>//<param name= "model" > Models </param>///<returns> successful </returns& Gt public bool Edit (Syssamplemodel model) {try {syssample entity = Rep.getbyid ( Model. ID); if (entity = = null) {return false; } entity. NamE = model. Name; Entity. Age = Model. Age; Entity. Bir = model. Bir; Entity. Photo = model. Photo; Entity. Note = model. Note; if (Rep.edit (entity) = = 1) {return true; } else {return false; }} catch (Exception ex) {//exceptionhander.writeexception (ex); return false; }}///<summary>//To determine the existence of entities///</summary>//<param name= "id" > Primary key Id</param>//<returns> exists </returns> public bool Isexists (string id) { if (db. Syssample.singleordefault (A = a.ID = = Id) = null) {return true; } return false; }///<summary>///For an entity by ID///</summary> <param name= "id" >id</param>///<returns> entities </returns> public Syssamplemodel G Etbyid (string id) {if (Isexist (ID)) {syssample entity = Rep.getbyid (ID); Syssamplemodel model = new Syssamplemodel (); Model. Id = entity. Id; Model. Name = entity. Name; Model. Age = entity. Age; Model. Bir = entity. Bir; Model. Photo = entity. Photo; Model. Note = entity. Note; Model. Createtime = entity. Createtime; return model; } else {return new Syssamplemodel (); }}///<summary>//To determine if an entity exists///</summary>//<param name= "id" > Id</param>//<returns> presence true or false</returns> public bool Isexist (string ID) {return rep.isexist (ID); }}}syssamplebll.cs
Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;using App.BLL; Using app.ibll;using app.models;using app.models.sys;using microsoft.practices.unity;namespace app.admin.controllers{public class Syssamplecontroller:controller {//// GET:/syssample/ // /<summary>/// Business Layer Injection/// </summary> [Dependency] public isyssamplebll M_BLL {get; set;} Public ActionResult Index () { list<syssamplemodel> List = m_bll. GetList (""); return View (list);}} SysSampleController.cs
@model list<app.models.sys.syssamplemodel>@{Layout = null;} <! DOCTYPE html>
Because syssample in the BLL layer has been released, we have to pay attention to the view we have to change
Let's download the code and compare it with our 5th bad code. Our code is optimized, clear, the constructor can automatically free up memory, no need to instantiate.
Of course, the effect of the preview is the same
So that our system is injected, we need to understand this, and later we will demonstrate AOP aspect-oriented, the handling of system logs and exceptions.
We have 4 layers of abnormal capture, you are also afraid of your system in operation of an unknown error???? But again, we have to make our system more interesting first.
Next, the return JSON format is combined with the DataGrid for paging.
The code download code does not contain the Packages folder, your compilation may be wrong, the packages under your MVC4 project can be copied to the solution.
Build a back-end management system for ASP. Mvc4+ef5+easyui+unity2.x Injection (6)-unity 2.x dependency Injection by runtime injection [attached source]