. NET using Unity for AOP

Source: Internet
Author: User

Unity is a well-known dependency injection container that supports the expansion of functionality through custom extensions. An object interception (interception) extension definition is included by default within the unity package. This article describes how to use object interception to help you separate crosscutting concerns (separation of cross-cutting concerns).

Introduction to Object interception

Object interception is a practical approach to AOP (Aspect-oriented programming) programming. It helps you maintain the purity of your business class without having to consider peripheral concerns such as logs and caches.

In. NET, there are several ways to implement AOP. One way is to use a post-compilation approach, such as Postsharp. After compiling, postsharp modifies the IL code to such a crosscutting code.

In contrast, object interception is performed at run time, and also implies some limitations. Depending on the interceptor implementation, there are the following constraints:

    • Transparent proxy interceptors: you need to define interfaces, or require classes to inherit from MarshalByRefObject.
    • Interface interceptors: interfaces need to be defined.
    • Virtual method Interceptors: Only required methods are defined as virtual methods.
How object interception Works

When you request a target object from the Unity container, you will not get an instance of the configured class. In fact, you will get a dynamically generated proxy object, or a derived class.

If you invoke a method of a proxy object, you will be able to execute code that performs some extra behavior before or after the invoked method executes. Those classes that define behavior need to implement the Icallhandler interface. With these behavior definitions, we can access the parameter list of the method invocation, which can devour the exception, or can return a custom exception.

Incidentally, unity interceptors are also available without the use of unity containers.

Example: Logging exception and method invocation parameter lists to the log

In the example below, we will create two custom behaviors, all of which implement the Icallhandler interface:

    • Loggercallhandler: Records the method invocation parameter list to the log.
    • Exceptionloggercallhandler: The method invocation parameter list and exception information and the call stack are recorded in the log.

Exceptionloggercallhandler is defined as follows:

1InternalClassExceptionloggercallhandler:icallhandler2{3PublicImethodreturn Invoke (4Imethodinvocation input, Getnexthandlerdelegate getNext)5{6 Imethodreturn result =GetNext () (input, getNext);7if (result. Exception! =Null)8{9 Console.WriteLine ("Exceptionloggercallhandler:");Ten Console.WriteLine ("\tparameters:");11for (int i =0; I < input. Arguments.count; i++)12{13var parameter =Input. Arguments[i];14Console.WriteLine (15String. Format ("\t\tparam{0}, {1}", I, parameter. ToString ()));16}17Console.WriteLine ();Console.WriteLine ("Exception occured:");19Console.WriteLine (20String. Format ("\texception, {0}", result. Exception.Message));21st22Console.WriteLine ();Console.WriteLine ("StackTrace:");  Console.WriteLine (environment.stacktrace);  The   return result;  The public   int Order { get; set;} + }                    

To apply the behavior to the method, we need to create the appropriate handlerattribute to create an instance of the behavior.

1   class Exceptionloggerattribute:handlerattribute {override Icallhandler Createhandler (Iunitycontainer container) {new exceptionloggercallhandler (); } 7}         

In this example, we create a simple calculator class. In order to use the interface interception feature, we also need to create an interface type so that the specified behavior can be applied:

 1 public  Interface Icalculator2  {3  [Logger]4 int Add (int first,  second); 5 6  [exceptionlogger]< Span style= "color: #008080;" >7 int Multiply (int First, int second); 8}             

The calculator class is also implemented as usual. Now we need to configure the Unity container:

1 Iunitycontainer container =NewUnityContainer ();2 container. Addnewextension<interception>();3Container4. Registertype<icalculator, calculator>() 5. Configure<interception>() 6. Setinterceptorfor<icalculator> (new interfaceinterceptor ()); 7 8 // Resolve 9 ICalculator calc = container. Resolve<icalculator>();  Ten  //Call methodCalc. ADD (1, 2);                  

When you try to get an instance of a calculate class on a container by calling the Resolve method, you will get a proxy class instance. It may have a name similar to ' DynamicModule.ns.Wrapped_ICalculator_83093f794c8d452e8af4524873a017de '. When a method of this wrapper class is called, Callhandlers will be executed.

Summarize

Unity does not provide a complete AOP framework, so there are some limitations to using it. However, it is sufficient to implement some basic AOP requirements using the Unity Object Interception feature.

. NET using Unity for AOP

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.