Being armed with some new toys I wanted to carry on into my look of Alt.Net ways. This latest post is just a very quick demo of Aspect Oriented Programming (AOP), hopefully it will prove helpful to understand AOP for others as it did for me.
If you do not know what AOP is, please google or Wikipedia it
First things first. for this demo I'm using Spring.Net version 1.1.2 (almost the latest version)
Project Download: Test_Spring.zip (3.55 mb) (VS2008)
Project Overview
1. The Service Layer. (simple service)
This test app has a Service called "Hello" which implements the IHello. The main point of this is that the Hello.World function throws an exception, and the application is going to use AOP to jump in and show the params passed to the method.
Note if you did not use an interface or make the method virtual, the spring.Net framework does not apply the aspect.
namespace ServiceLayer
{
public class Hello : IHello
{
//The method which will throw the exception
public string World(string Name)
{
throw new Exception("did not work");
}
}
//The IHello contract
public interface IHello
{
string World(string Name);
}
}
2 Aspects
there are many types of aspects you can use, in this case I have used the IThrowAdvice, which will intercept an exception thrown. For more information see the Spring.Net Manual its really well written.
namespace Logging
{
public class Log : IThrowsAdvice
{
//catch any exception
public void AfterThrowing(MethodInfo method, object[] args, object target, Exception ex)
{
Console.WriteLine("");
Console.WriteLine("Test Logging, Params");
//print out all the params where were passed into the method
//which threw the exception.
foreach (object arg in args)
{
Console.WriteLine(arg.ToString());
}
//this will write the thrown exception msg
Console.WriteLine("Error Msg: " + ex.Message);
Console.WriteLine("End of logging");
}
}
}
3. The Command line app
Finally the command line app sets up the AOP container and calls the method. note there are a 2 ways (which i have seen) to set up AOP,
1 Is programmatic, shown below.
2 Is using the IoC container and XML, commented out, but i have included the XML in the attached project
namespace Test_Spring
{
class Program
{
static void Main(string[] args)
{
//// Create AOP proxy using Spring.NET IoC container.
//IApplicationContext ctx = ContextRegistry.GetContext();
//IHello hello = (IHello)ctx["HelloService"];
//Creating the AOp Factory in Code.
ProxyFactory factory =
new ProxyFactory(
new Hello());
factory.AddAdvice(
new Log());
IHello hello = (IHello)factory.GetProxy();
try
{
hello.World("Dave");
}
catch
{
//no logging here
}
Console.WriteLine("press Enter to Exit.");
Console.ReadLine();
}
}
}
Running this app you will see there is more written to the console than "press Enter to Exit", how cool is this? from what i can see if creates a virtual proxy class which inherites off the Hello class. Then when you call any function it is able to re-act accordingly!