Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#

Aspect Oriented Programming in .NET

Rate me:
Please Sign up or sign in to vote.
3.76/5 (21 votes)
14 Jun 2021CPOL8 min read 119.7K   114   5
An introduction to Aspect Oriented Programming in .NET

Index

Introduction

I just completed my second book ".NET Interview Questions" and am now on my third book "SQL Server 2005 Interview questions". Had a decent time in between to update my skills and be in tune with new developments. Thanks to my publisher for giving me a free pass for the Aspect Oriented Programming seminar in Mumbai, that's what has inspired me to write this article. A lot has been written about AOP (Aspect Oriented Programming) on the Web, but none of the articles cover how to implement it practically in C#.

Let's start with a small definition on AOP first:

"Aspect Oriented Programming is a methodology to separate cross cut code across different modules in a software system."

In short, all the cross cut code is moved to a separate module, thus increasing more modularity and bringing in ease of maintenance. Okay, that was a theoretical definition, let's try to understand why we really need AOP when we have decent methodologies like "Object Oriented Programming" and "Procedural Oriented Programming".

"Aspect oriented programming is not introduced in order to replace OOP, but assists it to remove its short comings. I see AOP as a brother of OOP".

Every Requirement Is a Concern

"Software development exists because of business concerns".

Software development is nothing but addressing a collection of concerns in real life. For instance, a customer sales software application has the following concerns:

  • User should be able to add, update and delete customer related information.
  • User should be able to track sales related to customer.
  • User should have a facility to print customer and sales information.
  • User should have a facility to email customer and sales information.

Okay, now readers will be wondering what's so special about these concerns, it can easily be implemented using OOP. In the next section, we will try to implement the above concerns using the OOP methodology and see why we need AOP.

Cross Cutting Concern and Tangled Code

Image 1

Figure 1.1 Class diagram for Customer Sales Software Application

Above is the class diagram for the Customer Sales Software Application discussed in the first section. We are trying to address the four concerns for the application: Customer Maintenance, Sales Maintenance, Printing and Sending Email. So by abiding to all laws of OOP, the above class diagram is drawn. "ClsCustomer" class is responsible for adding, updating and deleting the customer records. "ClsSales" class is responsible for maintaining sales information for a customer, you can see the link between "ClsCustomer" and "ClsSales" classes. There were also some technical concerns. Printing and sending email are addressed by "ClsPrint" and "ClsEmail" classes. Also note both classes "ClsCustomer" and "ClsSales" have a dependency relationship on both of these classes ("ClsPrint" and "ClsEmail") to achieve the technical functionality.

Now according to OOP literature, the first very important thing is that every object should be independent and should be concerned only about its functionality. Example, the "ClsCustomer" should only be concerned about adding, updating and deleting customer records. The Customer class should not have responsibilities of Sales or Print class. All the objects should work using messaging to achieve certain business functionality. In the above class diagram, all the classes are collaborating to make work the complete "Customer Sales Application".

OK, now it's time to look at the implementation of the above class diagram.

Image 2

Figure 1.2 Explorer look of Customer Sales Application

As dictated by the class diagram, all the classes are included in the Explorer. OK, let's look at one of the implementations, that is the customer class implementation, i.e., the "Add" method of the Customer class. Below is a paste of the "Add" method of the Customer class.

C#
public void Add()
{
  /////////////////////////////////////////
  // This method adds customer information
  // 
  // Adding code will go here
  ////////////////////////////////////////

  // After adding to database email is sent
  ClsEmail pobjClsEmail = new ClsEmail();
  pobjClsEmail.Send();

  // After sending email its printed
  ClsPrint pobjClsPrint = new ClsPrint();
  pobjClsPrint.Print();
}

Okay, the "Add" method of "ClsCustomer" is doing some really heavy duty like:

  • It adds the customer data to the customer database.
  • Then it sends email using the class "ClsEmail".
  • Finally, it prints the customer details using the "ClsPrint" class.

Don't you think guys "ClsCustomer" is doing some really heavy job, especially it's doing a lot of things which are not its concern. Example: sending email and printing is not its concern at all. Also note the same implementation has to be done with the "ClsSales" class. So in the Sales class also, we have to use both the classes: "ClsEmail" and "ClsPrint". In short, the "Print" and "Email" span across more than one module. Such types of concerns are called as "Cross Cut Concerns". The code over there is quite messed up as we are using lots of objects. These types of code are called as "Tangled code" in AOP terminology.

Okay, so here are some observations about concerns. All software applications have two types of concerns:

  • Core / Main concern (Example: Customer and Sales maintenance concerns)
  • Cross cut concerns (Printing, logging, sending email, etc. which spans across modules)

Now we are aware of our problem "tangled code".

Solution for Tangled Code: Weaving

Simply separate the Cross cut concerns from the Core concerns. So create modules for Cross cut and Core Concerns separately and then feed both the modules to the compiler. AOP supported compilers then compile both the modules and generate one single executable......isn't that cool guys? Hmmm... now how do we attain that with .NET compilers? Well, till now, .NET compilers did not support actual AOP compiling. So we had to do quiet a hack to attain AOP functionality in .NET. AspectJ is an AOP compiler which does AOP implementation for Java. But I hope the way .NET Framework is architected, it should not be a big deal to get AOP to action... can you hear me Microsoft, we trust you.

"Weaving is a process of compiling the Core and Cross cut concerns together".

Image 3

Figure 1.3 AOP weaver in action

In the coming sections, we will try to see the different kinds of weavers documented for AOP. Let us see which type of weaving we can implement in C#. But for now, let's try to understand some basic terminology which you will come across again and again.

Join Points, Point Cuts and Advice

Join points, Point cuts and Advice are some basics which you will need to understand for AOP.

Join point is a point where a concern will cross cut the main code. Join points can be a method call, function, constructor, etc. Join points are useful in identifying problem points in a code. In our customer sales application, we have two join points:

  • pobjClsEmail.Send();
  • pobjClsPrint.Print();

Point Cut tells when it should match a Joint Point. In the above example, I can say to match the email join point only when it's called in conjunction with "Invoke". Example:

C#
Invoke( pobjClsEmail.Send(); )

So I have defined my point cut with the Email joint point using the Invoke method.

Advice when defined decides the sequence of execution of advice code with respect to joint point. Advice code is the code which you want to execute before or after the joint point. In AOP, you can specify the advice code to execute before, around or after the joint point is matched.

Note: Whatever is the case before, after or around, point cut must trigger first.

So depending on what you have specified, the advice code will execute before, after or around the joint point. Like in our example, we will want to execute the send and print afterwards.

Types of AOP Compilers

OK, AOP compilers come in different flavors and the type of weaving decides what type of compiler it is. There are four types of compilers, or to be specific, weaving types in AOP:

  • Compile time weaving: This type of weaving happens at the compiler level and is not supported currently in .NET. But there are other compilers which I will discuss in my next part of the AOP tutorial. In compile time, Core concern code and the Cross cut code is weaved before being compiled to MSIL code. So before the JIT compilation takes place, using .NET compilers Aspect code is compiled and fed to the main compiler. There are many third party compilers which are available which extend the .NET compiler module and implement this feature. I am sure when Microsoft implements this feature in .NET compilers... it's going to be party time guys.
  • Link time weaving: This type of compilers compile core and cross cut code after the MSIL is generated. Again, this has to be done at linker level. So at this moment not supported, we will either have to use third party or wait for Microsoft's AOP compiler.
  • Run time weaving: This type of weaving is done by using the .NET runtime. In short, your code detects the Core, Cross cut, etc. and executes them at run time. This is supported at this moment in .NET and we will see how we can implement Run time weaving. Again, many AOP gurus do argue that it is not actual AOP... I leave that to the readers.

From my point of view, compiler is AOP featured when it has keyword support for Aspect, Join points, Point cut, Advice, etc. So till then, .NET guys can go around using the round about methods (which I will explain in the second part) to claim that .NET is AOP featured.

I hope I was able to explain the fundamentals of AOP. In the second part of this tutorial, we will see how we can implement the above AOP features in .NET.

OK guys, just a short note: do give me a feedback on my collection of .NET Interview questions on my website.

History

  • 22nd August, 2005: Initial version

For further reading do watch the below interview preparation videos and step by step video series.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect https://www.questpond.com
India India

Comments and Discussions

 
AnswerExisting compile time AOP weavers Pin
frblondin6-Mar-14 0:15
frblondin6-Mar-14 0:15 
GeneralGood work. Pin
MMuazzamAli15-Nov-11 8:11
MMuazzamAli15-Nov-11 8:11 
GeneralGood Article on AOP Pin
Rupesh Kumar Tiwari20-Oct-11 8:19
Rupesh Kumar Tiwari20-Oct-11 8:19 
GeneralAOP with PostSharp and Gibraltar Pin
that143guy@yahoo.com17-Aug-10 6:11
that143guy@yahoo.com17-Aug-10 6:11 
Questionhow to intercept nested method calls? Pin
Saeed Alg28-Apr-08 3:52
Saeed Alg28-Apr-08 3:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.