In this post I want to explain what the decorator pattern is, why it is useful and how you can implement it in a generic way using Castle.DynamicProxy.
What is the Decorator pattern?
Before we dive into the technical details, let us start with a recap about what the decorator pattern actually is:
Decorator is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors.
There are a lot of use cases where the decorator pattern can help, in this blog post I focus on one of them; using a decorator to handle cross cutting concerns(caching, error handling, logging, …) without polluting your original object.
I’ll show you an example where I introduce caching at the repository interface level.
How to integrate the decorator pattern in a generic way?
You don’t need a special library or anything to implement the decorator pattern in C#. However I would like to write it in a generic way without the need to create the same decorator over and over again for different interfaces. Therefore I will use Castle.DynamicProxy. It allows me to create lightweight .NET proxies on the fly at runtime. These proxy objects allow calls to members of an object to be intercepted without modifying the code of the class. These interception points are the perfect place to introduce our caching behavior.
We’ll start by creating our cache interceptor using Castle.DynamicProxy:
public class CacheInterceptor : IInterceptor | |
{ | |
private readonly AsyncCacheInterceptor _asyncInterceptor; | |
public CacheInterceptor(AsyncCacheInterceptor asyncInterceptor) | |
{ | |
_asyncInterceptor = asyncInterceptor; | |
} | |
public void Intercept(IInvocation invocation) | |
{ | |
_asyncInterceptor.ToInterceptor().Intercept(invocation); | |
} | |
} |
This interceptor only calls our async cache interceptor that contains the real caching logic:
public class AsyncCacheInterceptor : AsyncInterceptorBase | |
{ | |
private readonly IMemoryCache _cache; | |
public AsyncCacheInterceptor(IMemoryCache cache) | |
{ | |
_cache = cache; | |
} | |
protected override async Task InterceptAsync(IInvocation invocation, Func<IInvocation, Task> proceed) | |
{ | |
//Nothing to cache here --> method that returns a task has no return value, so there is nothing to cache | |
await proceed(invocation).ConfigureAwait(false); | |
} | |
protected override async Task<TResult> InterceptAsync<TResult>(IInvocation invocation, Func<IInvocation, Task<TResult>> proceed) | |
{ | |
var name = $"{invocation.Method.DeclaringType}_{invocation.Method.Name}"; | |
var args = string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString())); | |
var cacheKey = $"{name}|{args}"; | |
if (!_cache.TryGetValue(cacheKey, out TResult returnValue)) | |
{ | |
returnValue = await proceed(invocation).ConfigureAwait(false); | |
//IMPORTANT:Hard coded to one hour in this example but I would recommend to make this configurable | |
_cache.Set(cacheKey, returnValue, absoluteExpirationRelativeToNow:TimeSpan.FromHours(1)); | |
} | |
return returnValue; | |
} | |
} |
In this async interceptor we use an IMemoryCache
instance to cache the data and use the intercepted method name together with the method arguments to construct the cache key. This guarantees that when our method is called with different arguments the correct values are returned.
We register these interceptors in the DI container and also register the ProxyGenerator
singleton that is responsible for the proxy generation:
services.AddTransient<IInterceptor, CacheInterceptor>(); | |
services.AddTransient<AsyncCacheInterceptor>(); | |
services.AddSingleton(new ProxyGenerator()); |
The last step is to write the logic that wraps the object we want to create in the proxy and plugin our interceptor. As I want to do this in a generic way I have created extension methods on IServiceCollection
:
public static void AddProxiedTransient<TInterface, TImplementation> | |
(this IServiceCollection services) | |
where TInterface : class | |
where TImplementation : class, TInterface | |
{ | |
// This registers the underlying class | |
services.AddTransient<TImplementation>(); | |
services.AddTransient(typeof(TInterface), serviceProvider => | |
{ | |
// Get an instance of the Castle Proxy Generator | |
var proxyGenerator = serviceProvider | |
.GetRequiredService<ProxyGenerator>(); | |
// Have DI build out an instance of the class that has methods | |
// you want to cache (this is a normal instance of that class | |
// without caching added) | |
var actual = serviceProvider | |
.GetRequiredService<TImplementation>(); | |
// Find all of the interceptors that have been registered, | |
// including our caching interceptor. (you might later add a | |
// logging interceptor, etc.) | |
var interceptors = serviceProvider | |
.GetServices<IInterceptor>().ToArray(); | |
// Have Castle Proxy build out a proxy object that implements | |
// your interface, but adds a caching layer on top of the | |
// actual implementation of the class. This proxy object is | |
// what will then get injected into the class that has a | |
// dependency on TInterface | |
return proxyGenerator.CreateInterfaceProxyWithTarget( | |
typeof(TInterface), actual, interceptors); | |
}); | |
} | |
public static void AddProxiedSingleton<TInterface> | |
(this IServiceCollection services, TInterface instance) | |
where TInterface : class | |
{ | |
services.AddSingleton(typeof(TInterface), serviceProvider => | |
{ | |
// Get an instance of the Castle Proxy Generator | |
var proxyGenerator = serviceProvider | |
.GetRequiredService<ProxyGenerator>(); | |
// Find all of the interceptors that have been registered, | |
// including our caching interceptor. (you might later add a | |
// logging interceptor, etc.) | |
var interceptors = serviceProvider | |
.GetServices<IInterceptor>().ToArray(); | |
// Have Castle Proxy build out a proxy object that implements | |
// your interface, but adds a caching layer on top of the | |
// actual implementation of the class. This proxy object is | |
// what will then get injected into the class that has a | |
// dependency on TInterface | |
return proxyGenerator.CreateInterfaceProxyWithTarget( | |
typeof(TInterface), instance, interceptors); | |
}); | |
} |
There is only one thing left to do, we call one of this extension methods to register the object that should be proxied:
services.AddProxiedTransient<IAuth3Repository, Auth3Repository>(); |