Advice

Remember from before that advice is the cross-cutting code that we want to run transparently at several scattered points in the code. In Spring.Net, advice is applied at the method level and there are a few flavors of advice you can choose from.

Before Advice

Before advice is the most basic type of advice. It is a piece of cross-cutting code that runs before a method executes. Look at the following example of some before advice that logs the entrance to a method.

This advice will simply output the name of the executed method and the arguments passed in. This is a common example of some information that could be useful when debugging an application. (Note that, for the purposes of simplicity, you are just outputting the messages to the console. In a real application, you would want to use a more robust logging solution, such as log4net.)

A key point of this example is the implementation of the interface Spring.Aop.IMethodBeforeAdvice. This allows Spring.Net to recognize this code as before advice and run it where specified. To specify where this advice is applied, you turn to the core of any Spring.Net application, the XML configuration as defined in the App.config (or Web.config for web apps).

What we have done here is set up an AOP proxy for the example service and specified the before advice to intercept any call to a method within the example service. So, whenever one of the methods inside the example service is called, the before advice will run first and write the method logging information.

A key concept here is that you can apply this advice to multiple services if you want. In this example, you only apply the method logging advice to a single service. However, you could just as easily apply the same advice to other services at the same time, even if the services were completely unrelated. And, the great thing is that this is all achieved with configuration and not directly within the code. This reduces coupling because the code itself doesn't need to know who exactly it will be interacting with and can avoid unnecessary dependencies.

After Advice

After advice is fairly self-explanatory after looking at before advice. Instead of running the cross-cutting code before a method executes, after advice runs after the method executes.