Interception based Cross Cutting Concerns

Hiten Patel
Sep 9, 2018 · 2 min read

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 DecoratorService instead of ConcreteService to client code.
  • Calls to Logger, Security, Cache are made by DecoratorService instead of ConcreteService.

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).

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade