Unity v1.2 has a number of new features that make Unity a very impressive and usable dependency injection framework / IoC Container for your ASP.NET Webforms, ASP.NET MVC, WPF, and Windows Forms Applications.
Unity and AOP
One of my favorite new features in Unity is the Aspect-Oriented Programming ( AOP ) Features. Unity now has the core functionality in the Enterprise Library Policy Injection Application Block as well as two new interceptors, VirtualMethodInterceptor and InterfaceInterceptor, which are lightweight alternatives to the TransparentProxyInjector that works similar to the PIAB.
I already wrote tutorials on the TransparentProxyInjector and VirtualMethodInjector:
InterfaceInterceptor in Unity
I will assume you have read the two tutorials above, which offer a background explanation of the AOP Features and InterceptionExtension ( UnityContainerExtension ) in Unity v1.2.
Below is an example of using the new InterfaceInterceptor which works very similar to the VirtualMethodInterceptor. In this case, however, the Logger Class implements an ILogger Interface which makes the use of the InterfaceInterceptor possible for AOP.
using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
namespace InterfaceInterceptorExample
{
internal class Program
{
private static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
container.AddNewExtension<Interception>();
container.RegisterType<ILogger, Logger>().Configure<Interception>().SetInterceptorFor<ILogger>(
new InterfaceInterceptor());
var logger = container.Resolve<ILogger>();
logger.Write("World.");
}
}
public interface ILogger
{
[Test]
void Write(string message);
}
public class Logger : ILogger
{
public void Write(string message)
{
Console.Write(message);
}
}
public class TestAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new TestHandler();
}
}
public class TestHandler : ICallHandler
{
public int Order { get; set; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
Console.Write("Hello, ");
return getNext()(input, getNext);
}
}
}
The output to the console will be "Hello, World." Although you could use the various custom CallHandlers in the Enterprise Library Policy Injection Application Block, in this case I just created a custom ICallHandler and HandlerAttribute for letting the InterceptionExtension know that I want to intercept the Write Method on ILogger.
Conclusion
Although Unity v1.2 has not officially released, I assume it will have good documentation on the use of the TransparentProxyInterceptor, VirtualMethodInterceptor, and InterfaceInterceptor. I am looking forward to the documentation myself as the most productive way to learn AOP with Unity is not via the Unit Tests as I am now.
Read other Unity Tutorials and my Unity Screencasts.
David Hayden
Patterns & Practices Guidance