The IOC application and AOP application of Unity container in ASP.

Source: Internet
Author: User

In the ASP.NET-MVC framework, there is an example of using the Unity container to inject a custom controller factory. code example can download the source itself, here I will not say. The essence of the IOC container is the decoupled instantiation of the interface class, and how to decouple it is instantiated through a third-party container, where it is the unity container, not the interface class instantiated in the project. The method of instantiation is nothing but reflection, Emit, expression tree, delegate, etc. four methods. The IOC use of unity containers is primarily three methods: Register,resolver,dispose. The former registers interfaces and interface classes, which transfer instantiation of an interface class to a third-party container. And the dispose here is a bit of an article. If it's just a console application, you don't have to say, if it's in the MVC framework, where does the resource release for our interface class fit in? The Microsoft Unity Development team gave us a good explanation of the original:https://msdn.microsoft.com/en-us/library/dn178463 (v=pandp.30). aspx
We bind the release of the resources inside the Unity container with the resource release of the controller. How to use code to express? Instead of parsing an interface, we parse the Controllertype object in GetControllerInstance in the unity-based controller factory:
(IController) this. Unitycontainer.resolve (Controllertype);
Although the Unity container is an IOC framework, we can still use unity to do AOP, and we can refer to the official information:(5-interception using Unity)
We implement AOP primarily through the integration of the Icallhandler interface, which is provided by unity, which is primarily an invoke method. A class (Tcalhandler) that inherits from the Icallhandler interface begins invoking the Invoke method of the class (Tcalhandler) when the method in the class (Tiocimple) is invoked through the interface (Tiocinterface).
In invoke, if you call the GetNext () method, you call Iocimple the method that labels the property. If your C # foundation is solid, you should have an impression and a certain understanding of an important knowledge point-feature (attribute) in C #. Filters in the ASP.NET-MVC framework are implemented based on attribute. Well here too, we need to invoke unity to provide us with a feature attribute-handlerattribute, where we call our Icallhandler based class.
DI is an instantiated interface for understanding decoupling, whereas AOP is a horizontal injection of some logic, and we can implement the AOP module in di,unity by default to implement Di, and once we implement AOP, it is equivalent to implementing DI. I'll pick some code snippets to explain. Code from the <<ASP.NET-MVC framework secret >> the 14th chapter S1401 source code. First we implement our own custom controller factory:

 Public classunitycontrollerfactory:defaultcontrollerfactory{ PublicIunitycontainer UnityContainer {Get;Private Set; }  Publicunitycontrollerfactory (Iunitycontainer unitycontainer) { This. UnityContainer =UnityContainer; }    protected OverrideIController getcontrollerinstance (RequestContext requestcontext, Type controllertype) {if(NULL==Controllertype) {            return NULL; }        return(IController) This.    Unitycontainer.resolve (Controllertype); }}
View Code

The previously mentioned Unity di Object resolve is done here.

We define an interface Itimeprovider and an interface implementation class Defaulttimeprovider, and then we implement a class based on the Icallhandler interface:

 Public classcachingcallhandler:icallhandler{ Public intOrder {Get;Set ; }  PublicTimeSpan Expirationtime {Get;Private Set; }  Public StaticTimeSpan Defaultexpirationtime {Get;Private Set; }  Public StaticFunc<methodbase,Object[],string> Cachekeygenerator {Get;Private Set; } //Static constructors, called only once, and are the first to be called    StaticCachingcallhandler () {defaultexpirationtime=NewTimeSpan (0,5,0); Guid prefix=Guid.NewGuid (); Cachekeygenerator= (method, inputs) = ={StringBuilder SB=NewStringBuilder (); Sb. AppendFormat ("{0}:", prefix); Sb. AppendFormat ("{0}:", method.            DeclaringType); Sb. AppendFormat ("{0}:", method.            Name); if(Inputs! =NULL)            {                foreach(varInputinchinputs) {                    stringHashcode = (Input = =NULL) ?"": Input. GetHashCode ().                    ToString (); Sb. AppendFormat ("{0}:", hashcode); }            }            returnSb. ToString (). TrimEnd (':');    }; }     PublicCachingcallhandler (TimeSpan? expirationtime=NULL)    {         This. Expirationtime = Expirationtime.hasvalue?ExpirationTime.Value:DefaultExpirationTime; }     PublicImethodreturn Invoke (imethodinvocation input, getnexthandlerdelegate getNext) {MethodInfo Targetmethod =(MethodInfo) input.        MethodBase; if(Targetmethod.returntype = =typeof(void))        {            returngetNext () (input, getNext); }        Object[] inputs =New Object[input.        Inputs.count]; Input. Inputs.copyto (Inputs,0); stringCacheKey =Cachekeygenerator (Targetmethod, inputs); Object[] Cachedresult = HttpRuntime.Cache.Get (CacheKey) as Object[]; if(NULL==Cachedresult) {Imethodreturn Realreturn=getNext () (input, getNext); if(NULL==realreturn.exception) {HttpRuntime.Cache.Insert (CacheKey,New Object[] {realreturn.returnvalue},NULL, DateTime.Now.Add ( This.            Expirationtime), cache.noslidingexpiration); }            returnRealreturn; }        returnInput. Createmethodreturn (cachedresult[0],New Object[] {input.    Arguments}); }}
View Code

The invocation of the Invoke method triggers the call when the Itimeprovider object invokes its interface.
Next, a class is implemented based on Handlerattribute:

 Public classcachingcallhandlerattribute:handlerattribute{ PublicTimeSpan? Expirationtime {Get;Private Set; }  PublicCachingcallhandlerattribute (stringExpirationtime ="")    {        if(!string.            IsNullOrEmpty (Expirationtime)) {TimeSpan expirationtimespan; if(! Timespan.tryparse (Expirationtime, outExpirationtimespan)) {                Throw NewArgumentException ("Invalid input expiration Time (TimeSpan)"); }             This. Expirationtime =Expirationtimespan; }    }     Public Overrideicallhandler Createhandler (Iunitycontainer container) {return NewCachingcallhandler ( This. Expirationtime) {Order = This.    Order}; }}
View Code

Next we global.asax to complete the injection of AOP:

New UnityContainer (). Addnewextension<Interception>(). Registertype<itimeprovider, defaulttimeprovider>(); Unitycontainer.configure<Interception>(). Setinterceptorfor<ITimeProvider> (newnew  unitycontrollerfactory ( UnityContainer); ControllerBuilder.Current.SetControllerFactory (controllerfactory);
View Code

The last is the use of:

 Public classhomecontroller:controller{ PublicItimeprovider Timeprovider;  PublicHomeController (Itimeprovider _time) {Timeprovider=_time; }     Public voidIndex () { for(inti =0; I <3; i++) {Response.Write (string. Format ("{0}: {1:hh:mm:ss}<br/>","UTC", This.            Timeprovider.getcurrenttime (DATETIMEKIND.UTC)); Thread.Sleep ( +); Response.Write (string. Format ("{0}: {1:hh:mm:ss}<br/><br/>","Local", This.            Timeprovider.getcurrenttime (datetimekind.local)); Thread.Sleep ( +); }    }}
View Code

The Invoke method is called when the method GetCurrentTime method is Timeprovider during the call period. The invocation of the Invoke method parameter Getnexthandlerdelegate class variable in invoke represents the real call to the GetCurrentTime method. In fact, we can achieve this:

 Public Imethodreturn Invoke (imethodinvocation input, getnexthandlerdelegate getNext) {        var retvalue = getNext () (input, getNext);     if (RetValue. exception!=null)    {        Console.WriteLine ("error") ;    }     return RetValue;}
View Code

This simple implementation is perfectly possible.

Suggest to look at Microsoft Official information https://msdn.microsoft.com/en-us/library/ff647202.aspx
Code address: Link: Https://pan.baidu.com/s/1q98_Otwt1YC_00z_xcavIA Password: B9PJ

The IOC application and AOP application of Unity container in ASP.

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: 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.