Wednesday, November 5, 2014

A bit about AOP in .NET

Today I learned a little about Aspect Oriented Programming (AOP) in .NET.

Basically, AOP is where you can add functionality to your system without altering the business logic code. It allows developers to add with a clean separation of concerns. For example, if you want to log all exceptions in a certain way, you could either wire up the logger to all your methods, or use exception logging as an aspect that you can add to all methods.

The way you hook in the exception logging would be to write your logging method, write your aspect method to wrap method calls in a try-catch, then use either an IoC container to wrap your classes or an IL rewriter to rewrite your compiled code to wrap them.

The added functionality is called advice, where you hook in is called a joint point, and you can filter joint points to get pointcuts. A pointcut is a specific point that you want to target (like a specific method with certain input values).

Here's a bit about each approach:

IoC - IoC frameworks wrap your implementation of an interface in a proxy that implements the same and when you request the implementation from the container, you get the proxy. If the framework offers a way to intercept the method call, you can add your functionality to the method implementation.

IoC frameworks take a bit of work to set up and work best if you write good OO. Once you have that, you can rock your socks off and stop repeating yourself.

IL rewrite - you write your code, then your wrappers. When you compile the assembly, it needs to run through some post-production process to weave the aspect code into the business code.

Generally, AOP is beneficial since it allows you to separate system logic from business logic. Functional requirement code, from non-functional requirement code. Also, when unit testing your BL, all the other stuff can stay out of the way if you do it right (keep them separate until you integrate, then test the integrations).

I would recommend keeping the BL, the AOP, and the wiring code each in separate assemblies so that they can be composed into different arrangements (one for unit testing and one for production). Adding the aspect should be configurable, so you could even have different wrappers for each environment. This is a clear drawback of automatic IL weaving on build if it does not allow it to be done dynamically.

Another approach is to apply AOP to message bases interactions by intercepting the messages. This can be done in WCF by hooking into the message pipe. The forthcoming Actor Model implementation known as Orleans may or may not offer the ability to intercept messages, I haven't has the opportunity to explore it yet.

In summation, AOP is a great way to apply SOC so plan your development efforts accordingly so that you can use it later without modifying too much code to make it hook correctly.

No comments:

Post a Comment