Aspect Oriented Programming with Spring and Generics

posted @ Wednesday, September 28, 2005 2:56 AM

 

I wanted to post this example to flesh out an idea I was thinking about earlier today. Suppose you wanted to check permissions of a user before they made a method call, you might suggest an implementation of code access security. While that's a fair suggestion, I'd like to throw another option into the mix. With aspect oriented programming using the Spring framework, you can effectively check permissions before a method is called through the use of a proxy object that dispatches your calls to interceptors, that subsuquently invoke the requested call. Thus, depending on the results of your permission check, you can decide if you want to call the requested method or not. Here is a quick example implemented with generics. In the example, within the SecurityInterceptor you would check permissions which would allow you to control the Proceed call of the IMethodInvocation interface. Thoughts?

using System;
using
AopAlliance.Intercept;
using
Spring.Aop.Framework;
using
Spring.Aop.Interceptor;

namespace
DeveloperNotes
{
public class SecurityInterceptor : IMethodInterceptor
{

public object Invoke(IMethodInvocation invocation)
{
Console.WriteLine(
"Before: invocation=[{0}]", invocation);
object
rval = invocation.Proceed();
Console.WriteLine("Invocation returned");
return
rval;
}
}

public class ObjectFactory
{
public static K CreateObject<T, K>()
{
T obj
= Activator.CreateInstance<T>();
if
(obj != null)
{
ProxyFactory factory
= new ProxyFactory(obj);
factory.AddAdvice(new SecurityInterceptor());
return
(K)factory.GetProxy();
}
return default(K);
}
}

public interface IPerson
{
string Name
{
get;
set;
}

void SayHello();
}

public class Person : IPerson
{

private string name = string.Empty;

public string
Name
{
get{return name;}
set{name = value;}
}

public void SayHello()
{
Console.WriteLine(
"Hello {0}", this.Name);
}
}

class Program
{
static void Main(string[] args)
{
IPerson p
= ObjectFactory.CreateObject<Person, IPerson>();
if
(p != null)
{
p.Name
= "Nick";
p.SayHello();
}
Console.Read()
;
}
}
}