Unity and AOP
Unity and AOP: InterfaceInterceptor Example.
One of the solution architecture design key decisions is the cross-cutting concerns handling.
When we look at many of these cross-cutting concerns, we can recognize a pattern. Many of them happen only at either the start or the end of a method:
This leads to a different approach to implementing cross-cutting concerns. We can put some special handling before or after method calls , get the code out of the methods and enhance its maintainability.
The Unity 1.2 Interception extension lets us do just that.
Interception is a design pattern that is designed for cross-cutting concerns. Unity 1.2 provides support for interception through the Interception container.
The Unity Interception extension ships with two instance interceptors and one type interceptor:
Selection of a specific interceptor depends on your specific needs, because each one has various tradeoffs.
Below is an example of using the InterfaceInterceptor which works very similar to the VirtualMethodInterceptor,but, in current case the Logger Class implements an ILogger Interface which makes the use of the InterfaceInterceptor possible for AOP.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
namespace UnityAOPDemo
{
class Program
{
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
container.AddNewExtension<
Interception>();container.RegisterType<ILogger, Logger>(); container.AddNewExtension<Interception>();
container.Configure<
Interception>().SetInterceptorFor<ILogger>(new InterfaceInterceptor()); var logger = container.Resolve<ILogger>();
logger.Write(
"Hello World...");Console.ReadKey();
}
}
public interface ILogger
{
[
Log] void Write(string message);
}
public class Logger : ILogger
{
public void Write(string message)
{
Console.WriteLine(message);
}
}
public class LogAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new LogHandler();
}
}
public class LogHandler : ICallHandler
{
public int Order { get; set; }public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
Console.WriteLine("Log before..., ");IMethodReturn msg = getNext()(input, getNext);
Console.WriteLine("Log after... ");return msg;
}
}
}