[Entlib] how to learn from Microsoft enterprise database 5.0-Step 10: decouple your system with unity-part5-use the interceptor of Unity

Source: Internet
Author: User

In the previous article, we introduced how to use unity to take over piab for interception, while Unity itself also provides interception processing similar to icallhandler.Program-- Iinterceptionbehavior, today's articleArticleIt is mainly about how to use iinterceptionbehavior and the built-in interceptor of unity.

The following is what we will introduce:

1. Create a custom interceptionbehavior

2. Advantages and disadvantages of the three interceptors

3. How to use the three interceptors

 

1. Create a custom interceptionbehavior

Iinterceptionbehavior and icallhandler are very similar. Let's look at the specific definitions.Code:

Public interface iinterceptionbehavior {bool willexecute {Get;} ienumerable <type> getrequiredinterfaces (); imethodreturn invoke (imethodinvocation input, wait getnext );}

1. The willexecute attribute indicates whether the interception behavior can be executed.

2. List getrequiredinterfaces, used to return the list of related interfaces required for interception.

3. Method invoke. For specific invocation methods, you can compile the relevant business logic code in this method.

After learning about the iinterceptionbehavior code, we can start to write custom interception behaviors. However, before that, we should first look at some related interfaces and classes required by the experiment:

Interface istudent:

 
Public interface istudent {string name {Get; set;} int age {Get; set;} void showinfo (); void virtualshowinfo ();}

Implementation class student1:

Public class student1: istudent {public void showinfo () {console. writeline ("Student name:" + this. name); console. writeline ("student age:" + this. age. tostring ();} Public Virtual void virtualshowinfo () {console. writeline ("virtual method call"); console. writeline ("Student name:" + this. name); console. writeline ("student age:" + this. age. tostring ();} private string _ name = "Gu lei"; Public string name {get {return _ name;} set {_ name = value ;}} private int _ age = 22; Public int age {get {return _ age;} set {_ age = value ;}}}

Virtualshowinfo is used to introduce virtualmethodinterceptor, which will be introduced later.

Now you can write specific interception behaviors. The interception behavior here is very simple. It is to output some characters before calling a specific method. The specific code is as follows:

Public class logbehavior: iinterceptionbehavior {Private Static readonly methodinfo = typeof (istudent ). getmethod ("showinfo"); Public ienumerable <type> getrequiredinterfaces () {return new [] {typeof (istudent)};} public imethodreturn invoke (imethodinvocation input, wait getnext) {// check whether the parameter has if (input = NULL) throw new argumentnullexception ("input"); If (getnext = NULL) throw new argumentnullexception ("getnext "); if (input. methodbase = methodinfo) {console. writeline ("start logging"); console. writeline ("log record completed"); console. writeline ("Start of calling a specific method"); Return getnext () (input, getnext);} else {return input. createmethodreturn (null) ;}} public bool willexecute {get {return true ;}}}

Pay attention to the following in the specific interception behavior class:

1. Because getrequiredinterfaces is an interface for returning interception, only istudent can be returned here.

2. Set the attribute willexecute to true, which indicates that it can be executed.

3. Define a static variable methodinfo to record the showinfo information of the method under the istudent interface. Because the invoke is executed multiple times during the actual interception process, therefore, the actual method to be intercepted must be processed. Only the showinfo method is called. If showinfo is called, the corresponding characters are output. If not, the input is called. the createmethodreturn method returns an invalid imethodreturn.

Next, let's take a look at how to use the unity container to call this interception behavior. The specific code is as follows:

 
Public static void testinterception () {container. addnewextension <interception> (); container. registertype <istudent, student1> (// transparent proxy interception // new interceptor <transparentproxyinterceptor> (), // interface interception, same as the above transparent Interception Effect, new interceptor <interfaceinterceptor> (), new interceptionbehavior <logbehavior> (), new interceptionbehavior <logbehavior2> (); var studentinfo = container. resolve <istudent> (); studentinfo. showinfo ();}

Note the following points:

1. A new extension addnewextension <interception> () must be added for the container ();

2. The interception action must have a corresponding Interceptor. The above Code uses transparentproxyinterceptor (transparent proxy interceptor) and interfaceinterceptor (interface interceptor) respectively)

3. You can add multiple interception actions for an interceptor to do more.

The configuration code file is as follows:

<Alias = "istudent" type = "unitystudyconsole. idemo. istudent, unitystudyconsole "/> <alias =" student1 "type =" unitystudyconsole. demo. student1, unitystudyconsole "/> <alias =" logbehavior "type =" unitystudyconsole. interceptionbehavior. logbehavior, unitystudyconsole "/> <alias =" logbehavior2 "type =" unitystudyconsole. interceptionbehavior. logbehavior2, unitystudyconsole "/> <container name =" F Orth "> <! -- Added interception extension for containers, if the following interception configuration is not added, an error is returned --> <extension type = "interception"/> <register type = "istudent" mapto = "student1"> <interceptor isdefaultfortype = "true" Type = "interfaceinterceptor"/> <interceptionbehavior type = "logbehavior"/> <interceptionbehavior type = "logbehavior2"/> </register> </container>

It is as follows:

 

Ii. Advantages and disadvantages of the three interceptors

Untiy has three built-in interceptors. The following describes the advantages and disadvantages of these three interceptors:

1,Transparentproxyinterceptor, Transparent proxy Interceptor (Instance interceptor), Use. Net Transparentproxy/realproxyTechnology to intercept

Advantage: all methods of objects (virtual, non-virtual, and interfaces) can be intercepted.

Disadvantage: The intercepted object must beImplements alalbyrefobject or an InterfaceThe processing speed is too slow.

2,Interfaceinterceptor, Interface interception (Instance interceptor), Use dynamic code to create a proxy class for interception.

Advantage: It can intercept all objects that implement interfaces and process faster than transparentproxyinterceptor.

Disadvantage: Only methods that implement a single interface can be intercepted.

3,Virtualmethodinterceptor, Virtual method Interceptor (Type Interceptor), uses dynamic code to construct a derived class instead of intercepting the original class.

Advantage: the processing speed is faster than transparentproxyinterceptor.

Disadvantage: only virtual methods can be intercepted.

After understanding the advantages and disadvantages of the three interceptions, we can select the interceptor as needed.

 

3. How to use three interceptors

Although there are three ways to use interceptors, two of them (transparentproxyinterceptor and interfaceinterceptor) have already been introduced in the above Code. This article mainly introduces how to use virtualmethodinterceptor.

Because virtualmethodinterceptor is special, it can only intercept virtual methods. In the interface definition process, methods in the interface cannot be defined as virtual, but the following must be done when virtualmethodinterceptor is used:

1. Add the virtual keyword to the specified method in the interface implementation class, as shown in the preceding method virtualshowinfo

2. Change the method used to obtain the interception behavior, for example, typeof (student1). getmethod ("virtualshowinfo"), and directly obtain the method from the specified class.

3. Modify the specific registration code as follows:

Public static void testvirtualmethodinterceptor () {container. addnewextension <interception> (); container. registertype <student1> (new interceptor <virtualmethodinterceptor> (), new interceptionbehavior <logbehavior3> (), new additionalinterface <istudent> (); var studentinfo = container. resolve <student1> (); studentinfo. virtualshowinfo ();}

We can see that the above Code directly adds interceptor and interception behavior to the specific implementation class, but because of its nature it still depends on the istudent interface, therefore, you also need to add an additional interface to register new additionalinterface <istudent> (). After this modification, the running effect will be the same as above.

The specific configuration code is as follows:

<Container name = "th"> <! -- Added interception extension for containers, if the following interception configuration is not added, an error is returned --> <extension type = "interception"/> <register type = "student1"> <interceptor isdefaultfortype = "true" type = "virtualmethodinterceptor "/> <interceptionbehavior type = "logbehavior3"/> <addinterface type = "istudent"/> </register> </container>

 

The above is all the content in this article. Thank you for reading this!

 

In other words, if you think this article is useful or valuable, move the cursor over [recommendation] and click it for me. Thank you very much!

 

Source codeDownload: Click here to download

 

Index of a series of articles on the learning path of Microsoft enterprise database 5.0:

Step 1: getting started

Step 2: Use the vs2010 + data access module to create a multi-database project

Step 3: Add exception handling to the project (record to the database using custom extension)

Step 4: Use the cache to improve the website's performance (entlib caching)

Step 5: Introduce the entlib. validation module information, the implementation level of the validators, and the use of various built-in validators-Part 1

Step 5: Introduce the entlib. validation module information, the implementation level of the validators, and the use of various built-in validators-Part 1

Step 5: Introduce the entlib. validation module information, the implementation level of the validators, and the use of various built-in validators-Part 2

Step 6: Use the validation module for server-side data verification

Step 7: Simple Analysis of the cryptographer encryption module, custom encryption interfaces, and usage-Part 1

Step 7: Simple Analysis of the cryptographer encryption module, custom encryption interfaces, and usage-Part 2

Step 8. Use the configuration setting module and other methods to classify and manage enterprise database configuration information

Step 9: Use the policyinjection module for AOP-PART1-basic usage

Step 9: Use the policyinjection module for AOP-PART2-custom matching rule

Step 9: Use the policyinjection module for AOP-PART3 -- Introduction to built-in call Handler

Step 9: Use the policyinjection module for AOP-PART4 -- create a custom call handler to achieve user operation Logging

Step 10: Use unity to decouple your system-Part1-Why use unity?

Step 10: Use unity to decouple your system-Part2-learn how to use Unity (1)

Step 10. Use unity to decouple your system-Part2-learn how to use Unity (2)

Step 10: Use unity to decouple your system-Part2-learn how to use Unity (3)

Step 10: Use unity to decouple your system-Part3-dependency Injection

Step 10: Use unity to decouple your system-part4 -- unity & piab

Step 10: Use unity to decouple your system-part5-use Unity's own interceptor

Extended learning:

Extended learning and dependency injection in libraries (rebuilding Microsoft Enterprise Library) [go]

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.