Member-only story
How to Improve .Net Applications with AOP
Learn how to configure dependency injection to make things happen by design
Completing tasks without writing code is the dream of any developer. In this article, we will learn a pattern that makes things happen without writing a line of code. The philosophy is AOP (Aspect-Oriented Programming). This technique is widely used in Java and helps to keep high-quality standards with low effort. Today we will learn how to use it also in .net core project with no pain. After a brief theoric explanation, you will find two examples (all the code is in my GitHub profile).

What is AOP
Let’s start from the Wikipedia definition:
In computing, aspect-oriented programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. It does so by adding additional behavior to existing code (an advice) without modifying the code itself […] This allows behaviors that are not central to the business logic (such as logging) to be added to a program without cluttering the code, core to the functionality. https://en.wikipedia.org/wiki/Aspect-oriented_programming
The concept is simple and can be summarized with one sentence.
Make things happen without writing code.
This applies to all the code that is needed but does not introduce any business logic.
Some examples of how AOP can change our code below. The first one is about logging.
public void SaveData(InputClass input)
{Stopwatch timer= new Stopwatch();
timer.Start();
logger.Info("enterd SaveData method");
if(logger.LogLevel==LoggingLeve.Debug)
{
logger.Debug(MyJsonTool.ConvertToJson(input);
}dataRepositoryInstance.Save(input); logger.Info($"enterd SaveData method in {timer.ElapsedMilliseconds}ms");}
What if I tell you that all this code can produce the same output just by writing this?
public virtual void SaveData(InputClass input)
{
dataRepositoryInstance.Save(input);
}