Aspect Oriented Programming With .Net

recep orhan
2 min readMar 20, 2021

AOP, making separation of cross-cutting concerns, aims to reusability, readability, and modularity.

What are the cross-cutting concerns? They are operations such as exception handling, logging, caching, security, performance management that we need at different layers and methods. Writing these codes to every method cause repetition. Also, complicating the readability and sustainability of software.

We write a method for one work but often write a lot of code before and after the main code for different purposes. We can see “some work” in this picture but in real life, it’s not easy to see “some work” in code blocks made up of text.

AOP programming paradigm lets us modulates the process that needed in other methods too. We can use AOP with using Method interception ve Reflection.

Interception: We can get some work done in method run time with interception. There are two types. The first one is, Codes are written to interception implemented methods at compile time. The second one is, codes are executed dynamically at run time. Autofac and Postsharp are the most popular libraries in .net for using interception.

Reflection: It is one of the useful features OOP provided us. We can get instances to a class, reach property names and data types, get method names, parameters, return types. Reflection helps us for using effectively AOP.

After this short description, let's start coding.

AOP with .Net

I write an abstract class then I derive AOP modules from this. For this infrastructure 3 nuget packages must be installed.

After installing 3 packages, the base class is written.

Giving the attribute feature to the base class, I can use AOP modules by writing above the class, like attribute.

Autofac module is used for dependency resolving, is written.

We can write a concrete AOP class at this point. I write the PerformanceAspect class derived from MethodInterceptionBaseAttribute for method operation time.

We are using PerformanceAspect like an attribute writing above the class.

When GetList business class calling, PerformanceAspect intercept and give us method operation time. We can use PerformanceAspect wherever needed with writing the above method one line of code. We get done all performance measurement, only with one line code. Also, Getlist method looks clear with the main purpose. We can write AOP modules for other purposes such as caching, logging, authorization, validation, transaction etc.

--

--