In this document
- Get the source code from the GitHub repository.
Introduction
In this article, I'll show you how to create interceptors to implement AOP techniques. I'll use ASP.NET Boilerplate (ABP) as the base application framework and Castle Windsor for the interception library. Apart from ABP framework, most of the techniques explained here are also eligible for using Castle Windsor.
What is Aspect Oriented Programming (AOP) and Method Interception?
From Wikipedia: "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, instead separately specifying which code is modified via a "pointcut" specification".
In an application, we may have some repeating/similar code for logging, authorization, validation, exception handling and so on...
Manual Way (Without AOP)
An example code that implements it all manually:
public class TaskAppService : ApplicationService
{
private readonly IRepository<Task> _taskRepository;
private readonly IPermissionChecker _permissionChecker;
private readonly ILogger _logger;
public TaskAppService(IRepository<Task> taskRepository,
IPermissionChecker permissionChecker, ILogger logger)
{
_taskRepository = taskRepository;
_permissionChecker = permissionChecker;
_logger = logger;
}
public void CreateTask(CreateTaskInput input)
{
_logger.Debug("Running CreateTask method: " + input.ToJsonString());
try
{
if (input == null)
{
throw new ArgumentNullException("input");
}
if (!_permissionChecker.IsGranted("TaskCreationPermission"))
{
throw new Exception("No permission for this operation!");
}
_taskRepository.Insert(new Task(input.Title, input.Description, input.AssignedUserId));
}
catch (Exception ex)
{
_logger.Error(ex.Message, ex);
throw;
}
_logger.Debug("CreateTask method is successfully completed!");
}
}
In CreateTask
method, the essential code is _taskRepository.Insert(...)
method call. All other code is repeating code and will be the same/similar for our other methods of TaskAppService
. In a real application, we will have many application services need the same functionality. Also, we may have other similar code for database connection open and close, audit logging and so on...
AOP Way
If we use AOP and interception techniques, TaskAppService
could be written as shown below with the same functionality:
public class TaskAppService : ApplicationService
{
private readonly IRepository<Task> _taskRepository;
public TaskAppService(IRepository<Task> taskRepository)
{
_taskRepository = taskRepository;
}
[AbpAuthorize("TaskCreationPermission")]
public void CreateTask(CreateTaskInput input)
{
_taskRepository.Insert(new Task(input.Title, input.Description, input.AssignedUserId));
}
}
Now, it exactly does what is unique to CreateTask
method. Exception handling, validation and logging code are completely removed since they are similar for other methods and can be centralized conventionally. Authorization code is replaced with AbpAuthorize
attribute which is simpler to write and read.
Fortunately, all these and much more are automatically done by ABP framework. But, you may want to create some custom interception logic that is specific to your own application requirements.
About the Sample Project
I created a sample project from ABP Download page (including login, register, user, role and tenant management pages) and added to the GitHub repository.
Creating Interceptors
Let's begin with a simple interceptor that measures the execution duration of a method:
using System.Diagnostics;
using Castle.Core.Logging;
using Castle.DynamicProxy;
namespace InterceptionDemo.Interceptors
{
public class MeasureDurationInterceptor : AbpInterceptorBase, ITransientDependency
{
public ILogger Logger { get; set; }
public MeasureDurationInterceptor()
{
Logger = NullLogger.Instance;
}
public override void InterceptSynchronous(IInvocation invocation)
{
//Before method execution
var stopwatch = Stopwatch.StartNew();
//Executing the actual method
invocation.Proceed();
//After method execution
stopwatch.Stop();
Logger.InfoFormat(
"MeasureDurationInterceptor: {0} executed in {1} milliseconds.",
invocation.MethodInvocationTarget.Name,
stopwatch.Elapsed.TotalMilliseconds.ToString("0.000")
);
}
//...
}
}
An interceptor is a class that implements AbpInterceptorBase
abstract class (of ABP). It defines the InterceptSynchronous
method which gets an IInvocation
argument. With this invocation argument, we can investigate the executing method, method arguments, return value, method's declared class, assembly and much more. InterceptSynchronous
method is called whenever a registered method is called (see registration section below). Proceed()
method executes the actual intercepted method. We can write code before and after the actual method execution, as shown in this example.
An Interceptor
class can also inject its dependencies like other classes. In this example, we property-injected an ILogger
to write method execution duration to the log.
Registering Interceptors
After we create an interceptor, we can register it for desired classes. For example, we may want to register MeasureDurationInterceptor
for all methods of all application service classes. We can easily identify application service classes since all application service classes implement IApplicationService
in ABP framework.
There are some alternative ways of registering interceptors. But, it's the most proper way in ABP to handle ComponentRegistered
event of Castle Windsors Kernel
:
internal static class MeasureDurationInterceptorRegistrar
{
public static void Initialize(IIocManager iocManager)
{
iocManager.IocContainer.Kernel.ComponentRegistered += (key, handler) =>
{
if (typeof (IApplicationService).IsAssignableFrom(handler.ComponentModel.Implementation))
{
handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(AbpAsyncDeterminationInterceptor<MeasureDurationInterceptor>)));
}
};
}
}
In this way, whenever a class is registered to dependency injection system (IOC), we can handle the event, check if this class is one of those classes we want to intercept and add interceptor if so.
After creating such a registration code, we need to call the Initialize
method from somewhere else. It's best to call it in PreInitialize
event of your module (since classes are registered to IOC generally in Initialize
step):
public class InterceptionDemoApplicationModule : AbpModule
{
public override void PreInitialize()
{
MeasureDurationInterceptorRegistrar.Initialize(IocManager);
//...
}
public override void Initialize()
{
//...
IocManager.Register(typeof(AbpAsyncDeterminationInterceptor<MeasureDurationInterceptor>), DependencyLifeStyle.Transient);
}
//...
}
After these steps, I run and login to the application. Then, I check log file and see logs:
INFO 2024-02-01 10:28:07,657 [orker] .Interceptors.MeasureDurationInterceptor - MeasureDurationInterceptor: GetCurrentLoginInformations executed in 3.633 milliseconds.
Note: GetCurrentLoginInformations is a method of SessionAppService class. You can check it in source code, but it's not important since our interceptor does not know details of intercepted methods.
Intercepting Async Methods
Intercepting an async method is different than intercepting a sync method. For example, MeasureDurationInterceptor
defined above does not work properly for async methods. Because, an async method immediately returns a Task
and it's executed asynchronously. So, we can not measure when it's actually completed (Actually, the example GetCurrentLoginInformations
above was also an async method and 3,633 ms was a wrong value).
Let's change MeasureDurationInterceptor to support async methods, then explain how we implemented it:
using Abp.Dependency;
using Castle.Core.Logging;
using Castle.DynamicProxy;
using System.Diagnostics;
using System.Reflection;
using System.Threading.Tasks;
namespace InterceptionDemo.Interceptors
{
public class MeasureDurationAsyncInterceptor : AbpInterceptorBase, ITransientDependency
{
public ILogger Logger { get; set; }
public MeasureDurationAsyncInterceptor()
{
Logger = NullLogger.Instance;
}
public override void InterceptSynchronous(IInvocation invocation)
{
//Before method execution
var stopwatch = Stopwatch.StartNew();
//Executing the actual method
invocation.Proceed();
//After method execution
stopwatch.Stop();
Logger.InfoFormat(
"MeasureDurationAsyncInterceptor: {0} executed in {1} milliseconds.",
invocation.MethodInvocationTarget.Name,
stopwatch.Elapsed.TotalMilliseconds.ToString("0.000")
);
}
protected override async Task InternalInterceptAsynchronous(IInvocation invocation)
{
var proceedInfo = invocation.CaptureProceedInfo();
//Before method execution
var stopwatch = Stopwatch.StartNew();
proceedInfo.Invoke();
var task = (Task)invocation.ReturnValue;
await task;
//After method execution
stopwatch.Stop();
Logger.InfoFormat(
"MeasureDurationAsyncInterceptor: {0} executed in {1} milliseconds.",
invocation.MethodInvocationTarget.Name,
stopwatch.Elapsed.TotalMilliseconds.ToString("0.000")
);
}
protected override async Task<TResult> InternalInterceptAsynchronous<TResult>(IInvocation invocation)
{
var proceedInfo = invocation.CaptureProceedInfo();
//Before method execution
var stopwatch = Stopwatch.StartNew();
proceedInfo.Invoke();
var taskResult = (Task<TResult>)invocation.ReturnValue;
var result = await taskResult;
//After method execution
stopwatch.Stop();
Logger.InfoFormat(
"MeasureDurationAsyncInterceptor: {0} executed in {1} milliseconds.",
invocation.MethodInvocationTarget.Name,
stopwatch.Elapsed.TotalMilliseconds.ToString("0.000")
);
return result;
}
}
}
The method within the AbpAsyncDeterminationInterceptor
is used to determine whether a method is asynchronous or not. This interceptor checks whether methods are asynchronous or not. I moved previous code to InterceptSync
method and introduced new InternalInterceptAsynchronous
method.
Now, I'm registering MeasureDurationAsyncInterceptor
as a second interceptor for application services by modifying MeasureDurationInterceptorRegistrar
defined above:
internal static class MeasureDurationInterceptorRegistrar
{
public static void Initialize(IIocManager iocManager)
{
iocManager.IocContainer.Kernel.ComponentRegistered += (key, handler) =>
{
if (typeof (IApplicationService).IsAssignableFrom(handler.ComponentModel.Implementation))
{
handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(AbpAsyncDeterminationInterceptor<MeasureDurationInterceptor>)));
handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(AbpAsyncDeterminationInterceptor<MeasureDurationAsyncInterceptor>)));
}
};
}
}
If we run the application again, we will see that MeasureDurationAsyncInterceptor
measured much more longer than MeasureDurationInterceptor
, since it actually waits until method completely executed.
INFO 2024-02-01 09:11:15,467 [orker] .Interceptors.MeasureDurationInterceptor - MeasureDurationInterceptor: GetCurrentLoginInformations executed in 2.010 milliseconds. INFO 2024-02-01 09:11:15,563 [orker] rceptors.MeasureDurationAsyncInterceptor - MeasureDurationAsyncInterceptor: GetCurrentLoginInformations executed in 1.201 milliseconds.
This way, we can properly intercept async methods to run code before and after.
We can execute async code after method execution. I changed InternalInterceptAsynchronous
like that to support it:
using Abp.Dependency;
using Castle.Core.Logging;
using Castle.DynamicProxy;
using System;
using System.Diagnostics;
using System.Reflection;
using System.Threading.Tasks;
namespace InterceptionDemo.Interceptors
{
public class MeasureDurationWithPostAsyncActionInterceptor : AbpInterceptorBase, ITransientDependency
{
public ILogger Logger { get; set; }
public MeasureDurationWithPostAsyncActionInterceptor()
{
Logger = NullLogger.Instance;
}
public override void InterceptSynchronous(IInvocation invocation)
{
//Before method execution
var stopwatch = Stopwatch.StartNew();
//Executing the actual method
invocation.Proceed();
//After method execution
LogExecutionTime(invocation, stopwatch);
}
protected override async Task InternalInterceptAsynchronous(IInvocation invocation)
{
var proceedInfo = invocation.CaptureProceedInfo();
//Before method execution
var stopwatch = Stopwatch.StartNew();
proceedInfo.Invoke();
var task = (Task)invocation.ReturnValue;
await TestActionAsync(invocation.MethodInvocationTarget.Name);
await task;
//After method execution
LogExecutionTime(invocation, stopwatch);
}
protected override async Task<TResult> InternalInterceptAsynchronous<TResult>(IInvocation invocation)
{
var proceedInfo = invocation.CaptureProceedInfo();
//Before method execution
var stopwatch = Stopwatch.StartNew();
proceedInfo.Invoke();
var taskResult = (Task<TResult>)invocation.ReturnValue;
await TestActionAsync(invocation.MethodInvocationTarget.Name);
var result = await taskResult;
//After method execution
LogExecutionTime(invocation, stopwatch);
return result;
}
private async Task TestActionAsync(string methodName)
{
Logger.Info($"Waiting after method execution for {methodName}");
await Task.Delay(200); // Here, we can await other methods. This is just for test.
Logger.Info($"Waited after method execution for {methodName}");
}
private void LogExecutionTime(IInvocation invocation, Stopwatch stopwatch)
{
stopwatch.Stop();
Logger.InfoFormat(
"MeasureDurationWithPostAsyncActionInterceptor: {0} executed in {1} milliseconds.",
invocation.MethodInvocationTarget.Name,
stopwatch.Elapsed.TotalMilliseconds.ToString("0.000")
);
}
}
}
Source Code
You can get the latest source code here https://github.com/aspnetboilerplate/aspnetboilerplate-samples/tree/master/InterceptionDemo