. Net Dynamic proxy Castle series (1)-preliminary understanding

Source: Internet
Author: User

Self-exposure to nhib.pdf, Spring. net and Moq frameworks have been around for a while. I think many Cool functions are implemented in these frameworks based on the dynamic proxy technology. I 'd like to share with you a little bit, I hope you can discuss and make progress together. My plan is that there will be four articles in this series:

1.. Net Dynamic proxy Castle series (1) --- preliminary understanding

2.. Net Dynamic proxy Castle series (ii) --- delay loading and implementation in ORM

3.. Net Dynamic proxy Castle series (iii) --- application and implementation in the Mock framework

4.. Net Dynamic proxy Castle series (4) --- Application and Implementation in AOP

Today, we will start to have a preliminary understanding of the dynamic proxy, and use instances to let everyone realize Castle and use it.

What is dynamic proxy? To better understand dynamic Proxy, You need to first understand the concept of Proxy. The concept of Proxy is everywhere in real life. For example, a house intermediary is a Proxy object, can act as an agent of the landlord (which can be understood as the Target). In addition, the intermediary can add some additional value to the landlord's power and intercept some actions of the landlord, such as charging an intermediary fee.

In the design pattern, there is a pattern called the proxy pattern, written in GOF as follows:

Provides a proxy for other objects to control access to this object.

Next, I will describe the story between the intermediary and the landlord in the form of code for your convenience.

First, abstract the landlord's interface.

   public interface ILandlordible    {        void RentHouse();    }

 

Create a landlord class and implement interfaces

Public class Landlord: ILandlordible {public void Guest House () {Console. WriteLine ("rent charged by the Landlord! ");}}

The landlord entrusts an intermediary for rent and now establishes an intermediary class:

Public class Intermediary: ILandlordible {private ILandlordible landlor; public Intermediary (ILandlordible landlor) {this. landlor = landlor;} private void CollectIntermediaryFees () {Console. WriteLine ("Intermediary service charge! ");} Public void hosted House () {landlor. Hosted House (); CollectIntermediaryFees ();}}

You can see the implementation of Intermediary.

1. First implement an ILandlordible interface because it will have the right to rent a house from a landlord

2. The class then stores the reference of ILandlordible because it will be delegated to the landlord.

3. In the housekeeping method, the intermediary first executes the actions of the landlord and then charges the intermediary fee.

Finally, the story between the intermediary and the landlord is coming soon:

Class required housestorygeneralproxyversion {static void main (string [] ARGs) {console. writeline ("the landlord entrusts an intermediary to rent a house! "); Ilandlordible landlord = new intermediary (new landlord (); console. writeline (" successfully rented house by intermediary "); landlord. Residential House ();}}

Execution result:

After completing the preceding example, you must have a certain understanding of the proxy mode. Next, we will explain the dynamic proxy mode in the future.

Dynamic proxy. In my understanding, the agent class is generated dynamically at runtime, and then the agent object is generated. In combination with the Mediation example, the intermediary class can be dynamically generated and there is no need to implement it on its own.

To dynamically generate or intercept one action, on the. NET platform:

1 .. in net remoting, webshells can be used to intercept objects, but the contextboundobject class must be displayed. In my opinion, this solution is not very good, because inheritance is often used only when there is a classless inter-class relationship, it is also subject to the limitation of single inheritance.

2. emit directly operates on IL, which is also a method, but I think it is too complicated and there is no need to study that depth, so I am not very recommended.

3. between the two methods described above, I chose the difficulty method, Castle. net is an open-source project, which has a dynamic proxy library that can be well solved. NET platform, such as Nhibernate and Moq.

Let me give you an example to adapt the mediation example to the dynamic Proxy version:

First, let's take a simple look at the proxygenerator class in Castle Based on the Proxy:

    public class ProxyGenerator    {        public ProxyGenerator();        public ProxyGenerator(IProxyBuilder builder);        public IProxyBuilder ProxyBuilder { get; }        public T CreateClassProxy<T>(params IInterceptor[] interceptors);    }

Here I have extracted some parts of ProxyGenerator. This class can be seen from the name that it can dynamically generate proxies for us, but think carefully about the goals of proxies, for example, if an intermediary acts as the landlord, the CreateClassProxy generic method is to specify the proxy target, so that a specific class can generate a proxy. However, it is not enough to specify a target. For example, in addition to the landlord's responsibilities, the agent has its own extra logic, such as service charges. Therefore, CreateClassProxy provides a variable parameter IInterceptor array. Let's take a look at the IInterceptor interface.

   public interface IInterceptor    {        void Intercept(IInvocation invocation);    }

When I call CreateClassProxy and pass in an object that implements IInterceptor, all methods will be intercepted by the Intercept method of IInterceptor, in addition, the IInvocation parameter of Interceptor carries all information about the called method, so that we can fully intercept the called method and do whatever we want.

Let's get started with the story between our dynamic proxy edition's intermediary and the landlord:

Continue to use the previous ILandlordible interface, but for the Landlord (Landlord) class, because it needs to generate a proxy class, the principle is to inherit from the Landlord class, the method of the source class is overloaded, with polymorphism, the interface is used to call the overload method, so the source class is modified:

Public class Landlord: ILandlordible {public virtual void Guest House () {Console. WriteLine ("rent charged by the Landlord! ");}}

The modification is to change the method of the source class to the Virtual method. If we see friends who have used nhib.pdf here, do they think it seems a bit similar? This is why the entity attribute of nhib.pdf needs to be added with the Virtual keyword, I will share the cause with you in the next article.

As for the Intermediary (Intermediary) class, it will be generated by dynamic proxy, so it will no longer be used. The core of the problem now is how to use Castle to implement the proxy class and add the logic for charging service fees.

First, create an interceptor to implement the IInterceptor interface.

Public class IntermediaryIntercetor: IInterceptor {public void Intercept (IInvocation invocation) {// execute the logic invocation of the landlord. proceed (); CollectIntermediaryFees ();} private void CollectIntermediaryFees () {Console. writeLine ("service fee charged by the intermediary! ");}}

With this interceptor, you can start the dynamic Proxy version:

Class required housestroydynamicproxyversion {static void main (string [] ARGs) {console. writeline ("the landlord entrusts an intermediary to rent a house! "); Landlord proxylandlord = createlandlordproxy (); console. writeline ("successfully rented house by intermediary"); proxylandlord. invalid House ();} Private Static landlord createlandlordproxy () {proxygenerator = new proxygenerator (); landlord proylandlord = proxygenerator. createclassproxy <landlord> (New intermediaryintercetor (); Return proylandlord ;}}

Execution result:

  

 

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.