Interception based Cross Cutting Concerns
Cross cutting concerns (logging, caching, security, etc.) poses 2 design challenges:
- Modularity: they are not contained within well defined modules (as they are referenced from many places) affecting code refactoring.
- Simplicity: they are mashed up with business logic making code readability poor.
In this article, I’ll describe already available technique to address these problems.
Illustrative Example
This sample code demonstrates how a simple method gets convoluted due to calls for cross cutting concerns, making it difficult to understand how logic is implemented.
SomeMethodWithBLandCCC(data)
{
log("DoSomething called with" + data);
if (!isUserAuthorized(user))
{
log("User does not have permission " + user);
throw new UnAuthorizedException();
}
if (cache.Contains(data))
{
log("Returning cached result " + result);
return cache[data];
} var result = perform_calculation_here
cache[data] = result;
log("Returning calculated result " + result);
return result;
}
Solution
Many IoC containers ex: AutoFac, Unity, etc. optionally support interception based on Decorator pattern. This option creates wrapper on object instances such that custom code can be executed before and/or after object methods are invoked.
The custom code can be calls to cross cutting concerns making original objects free of them (and comprised purely of business logic).

Object instantiation and end-to-end call sequence for such an implementation is as demonstrated in Sequence diagram below. Note that:
- IOC returns instance of
DecoratorServiceinstead ofConcreteServiceto client code. - Calls to
Logger,Security,Cacheare made byDecoratorServiceinstead ofConcreteService.

Code Sample
Refer https://github.com/hitenpatel01/Autofac-Interception for sample project that implements this technique using Autofac.
Conclusion
Dependency Injection has started being commonly used in software development making this technique readily available; it’s primarily just a choice of IoC container that supports interception (though one more consideration is it’s applicable only to public virtual methods, similar to limitation in mocking methods for Unit Testing).