Dora.interception, an AOP framework built for. NET Core: A new version

Source: Internet
Author: User

Dora.interception 1.0 (GitHub address: can access GitHub address: Https://github.com/jiangjinnan/Dora) launched for some time now, Recently it took some time to upgrade it to 2.0, mainly with the following improvements:

    • Provides a native dynamic proxy to generate the underlying framework Dora.dynamicproxy: Before relying on the third-party framework castle to achieve the lowest-level proxy generation, but it does not support task-based parallel programming (that is, the interceptor written through it cannot implement asynchronous execution), so I use IL Emit's way of doing this is self-fulfilling, and these bottom-up features are implemented in Dora.dynamicproxy.
    • The following two types of interception scenarios are available:
      • Case-based encapsulation: if the type of consumption is an interface, the provided type is a dynamically generated proxy class that encapsulates the target object. For each dynamically generated interface implementation member, it is responsible for executing the interceptor of the application. If the target method needs to be called, the corresponding method of the encapsulated target object is called. This interception scheme requires that the target type implement an interface, and all methods and properties defined in the interface can be intercepted.
      • Type-based inheritance: If the target type is a non-sealed type, an inheritance with its proxy type is dynamically generated. If interceptor is applied to a virtual method or property of the target type, the member is overridden in the generated proxy class, allowing interceptor to execute. This interception mechanism is suitable for non-sealed types, and only virtual methods/properties can be intercepted.
    • Provides blocking support for attributes: Previous versions support interception of methods, and blocking support for attributes is available in the latest version. We can choose to apply interceptor to a property of a type, or to a get or set method of that property, individually.
I. Support for task-based parallel programming

Since Dora.interception builds the framework for Dora.dynamicproxy as the default dynamic proxy type, it is not dependent on any third-party framework, so it's easier to program, so let's do a simple demo. After installing the latest version of the NuGet package dora.interception, we can define a simple interceptor type as follows in the "Contract" way. To verify support for task parallel programming, we deliberately delay a second in the interception method InvokeAsync.

 Public classfoobarinterceptor{Privateinterceptdelegate _next;  PublicFoobarinterceptor (interceptdelegate next) {_next=Next; }     Public AsyncTask InvokeAsync (Invocationcontext context) {Console.WriteLine ("interception task starts."); awaitTask.delay ( +); Console.WriteLine ("interception task completes."); await_next (context); }}

I distinguish between interceptor and interceptor, and the registration of interceptor is implemented by default in the form of feature annotations, For this we create a corresponding attribute type Foobarattribute for the foobarinterceptor defined above. As shown in the following code fragment, Foobarattribute derived from Interceptorattribute,foobarinterceptor is built in the overridden use method, You can specify the location (Order) of the interceptor throughout the interceptor chain during the build process.

[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method |  publicclass  foobarattribute:interceptorattribute{     public  Overridevoid use (Iinterceptorchainbuilder builder)    {        Builder. use <FoobarInterceptor> (this. Order);}    }

Next we define a simple type demo to use Foobarinterceptor,demo to implement the interface Idemo,foobarattribute callout on the method invokeasync that needs to be intercepted.

 Public Interface idemo{    Task invokeasync ();}  Public class demo:idemo{    [Foobar]    public  Task invokeasync ()    {        Console.WriteLine (  TheTarget method is invoked. " );         return task.completedtask;}    }

Since Dora.interception has achieved seamless integration with. NET Core's dependency injection, we only need to provide the service instance in a way that we are familiar with. As shown in the following code snippet, we registered the mapping relationship between Idemo and demo to the created Servicecollection, and did not call the Buildeserviceprovider method. Instead, call Buildinterceptableserviceprovider to create the serviceprovider that provides the service.

classprogram{Static voidMain (string[] args) {        varDemo =Newservicecollection (). Addsingleton<idemo, demo>()                 . Buildeinterceptableserviceprovider (). Getrequiredservice<IDemo>(); Demo.        InvokeAsync (); Console.WriteLine ("Continue ...");    Console.read (); }}

As shown below is the result of the execution of this code, we can see that the application's foobarinterceptor is executed normally, and it is executed entirely asynchronously.

Second, the interception based on virtual method

If the demo does not implement any interface, and it is not a sealed type, its virtual methods and properties can also be intercepted. For example, we have made the following changes to the demo.

 Public class demo{    [Foobar]    publicvirtual  Task invokeasync ()    {        Console.WriteLine ("Target method is invoked. " );         return task.completedtask;}    }

All demo has no interface implementation, so we need to modify the service registration code accordingly. After executing the revised code, we will still get the same output.

classprogram{Static voidMain (string[] args) {        varDemo =Newservicecollection (). Addsingleton<demo, demo>()                 . Buildeinterceptableserviceprovider (). Getrequiredservice<Demo>(); Demo.        InvokeAsync (); Console.WriteLine ("Continue ...");    Console.read (); }}
Third, attributes can also be intercepted

For the previous version, blocked members are limited to normal methods, and the latest version adds support for attributes. If a interceptor is applied directly to a property, it is actually applied to both the get and set methods of the property. For example, we add a Value property on the demo type and Foobarattribute on the standard above.

 Public class demo{    [Foobar]    publicvirtualobjectgetset;}}

Next we get a demo object as follows and call the set and get methods of its Value property.

classprogram{Static voidMain (string[] args) {        varDemo =Newservicecollection (). Addsingleton<demo, demo>()                . Buildinterceptableserviceprovider (). Getrequiredservice<Demo>(); Console.WriteLine ("Set ..."); Demo. Value=New Object(); Console.WriteLine ("Get ..."); varValue =Demo.        Value;    Console.read (); }}

As can be seen from the output below, the foobarinterceptor that we register on the Value property is executed once when the get and set methods are called.

If we only need to apply a interceptor to a property's get or set method, we can also make a specific annotation. In the code snippet below, we will foobarattrbute the standard to the Get method.

 Public class demo{    publicvirtualobjectgetset;}}

Executing the program again, we will find that Foobarinterceptor was executed only once when it called the Get method of the Value property.

Dora.interception, an AOP framework built for. NET Core: A new version

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.