Issue 22

AOP using Unity

Radu Vunvulea
Solution Architect


In the last number of Today Software Magazine we talked about the base principles of AOP and how we can implement the base concept of AOP using features of .NET 4.5, without using other frameworks. In this article we look at Unity and see how we can use this framework to implement AOP.


Before this, let's see if we can remember what is AOP and how we can use it in .NET 4.5 without any other frameworks.

Aspect Oriented Programming (AOP) is a programming paradigm with the main goal of increasing modularity of an application. AOP tries to achieve this goal by allowing separation of cross-cutting concerns, using interception of different commands or requests.

A good example for this case is the audit and logging. Normally, if we are using OOP to develop an application that needs logging or audit we will have in one form or another different calls to our logging mechanism in our code. In OOP this can be accepted, because this is the only way to write logs, to do profiling and so on. When we are using AOP, the implementation of the logging or audit system will need to be in a separate module. Not only this, but we will need a way to write the logging information without writing code in other modules that make the call itself to the logging system, using interception.

This functionality can be implemented using the tools inside .NET 4.5 like RealProxy and Attribute. RealProxy is special ingredient in our case, giving us the possibility to intercept all the request that are coming to a method or property.


This is a framework well known by .NET developers as a dependency injection container. It is part of the components that form Microsoft Patterns and Practices and the default dependency injection container when for ASP.NET MVC application. Unity reached the critical point in the moment when it was fully integrated with ASP.NET MVC. From that moment thousands of web project started to use it.

From a dependency injection container perspective, Unity is a mature framework that has all the capabilities that a developer expects to find at such a framework. Features like XML configuration, registration, default or custom resolver, property injection, custom containers are full supported by Unity.

In the following example we will see how we can register the interface IFoo in the dependency injection container and how we can get a reference to this instance.

IUnityContainer myContainer = new UnityContainer(); 
myContainer. RegisterInstance( new Foo()); 
IFoo myFoo = myContainer.Resolve();

When it is used with ASP.NET MVC, developers don't need to manage the lifetime of resources used by Controllers any more, Unity manages this for them. The only thing that they need to do is to register these resources and request them in the controller, like in the following example:

public class HomeController : Con
	Foo _foo;

	public HomeController(Foo foo)
		_foo = foo;

    public ActionResult Index()
        ViewData["Message"] = "Hello World!";

        return View();

    public ActionResult About()
        return View();

As we can see in the above example, Unity will be able to resolve all the dependences automatically.

Unity and AOP

Before looking in more details at this topic, we should set the expectation at a proper level. Unity is not an AOP framework, because of this we will not have all the features that form AOP.

Unity supports AOP at the interception level. This means that we have the possibility to intercept calls to our object from the dependency injection container and configure a custom behavior at that level.

Unity gives us the possibility to inject our custom code before and after a call of our target object. This can be done only to the objects that are registered in Unity. We cannot alter the flow for objects that are not in Unity container.

Unity offers us this feature using a similar mechanism that is obtained by the Decorated Pattern. The only difference is that in Unity case, the container is the one that decorates the call with a 'custom' attribute - behavior. At the end of the article we will see how easy it is to add a tracing mechanism using Unity or to make all the calls to database to execute using transactions.

We can use Unity for objects that were created by Unity and registered in different containers or objects that were created in other places of our application. The only request from Unity is to have access to these objects in one way or another.

How can Unity intercept calls?

All the client calls for specific types go through Unity Interceptor. This is a component of the framework that can intercept all the calls and inject one or more custom behavior before and after the call. This means that between the client's call and target object, Unity Interceptor component will intercept the call, trigger our custom behavior and make the real call to the target object.

All these calls are intercepted using a proxy that needs to be configured by developer. Once the proxy is set, all the calls will go through Unity. There is no way for someone to 'hack' the system and bypass the interceptor.

The custom behavior that is injected using Unity can change the value of input parameter or the returned value.

How to configure the interception?

There are two ways to configure the interception - from code or using configuration files. In both cases, we need to define custom behavior that will be injected in Unity containers. Personally I prefer to use the code, using the fluent API that is available. I recommend to use the configuration files only when you are sure that you will need to change configuration at runtime or without recompiling the code. Even if I recommend this way, in all the cases we used configuration from files (it is more flexible).

When you are using configuration files, you have a risk to introduce configuration issues more easily - misspelling name of the classes or make a rename of a type and forget to update the configuration files also.

The first step is to define the behavior that we want to execute when the interception of call is done. This is made only from code, implementing IInterceptionBehavior.

The most important method of this interface is 'Invoke', which is called when someone calls the methods that are intercepted. From this method we need to make the call itself to the real method. Before and after the call we can inject any kind of behavior.

Here, I would expect to have two methods, one that is called before the call itself and one after the call. But, we don't have this feature in Unity. Another important component of this interface is 'WillExecute' property. Only when this property is set to TRUE, the call interception will be made.

Using this interface we have the possibility to control the calls to any methods from the objects of our application. We have the full control to make a real call or to fake it.

public class FooBehavior : IInterceptionBehavior
  public IEnumerable GetRequiredInterfaces()
    return Type.EmptyTypes;
  public IMethodReturn Invoke(IMethodInvocation input, 
    GetNextInterceptionBehaviorDelegate getNext)
	Trace.TraceInformation("Before call");
    // Make the call to real object 
    var methodReturn = getNext().Invoke(input, getNext);
     Trace.TraceInformation("After call");
     return methodReturn;
   public bool WillExecute
     get { return true; }

Next, we need to add this custom behavior to Unity. We need to add a custom section to our configuration file that specifies what type we want to make this interception for. In the next example we will make this interception only for Foo type.


In this example, we specify to Unity to use the interface interceptor using FooBehavior for all the instances of IFoo objects that are mapped to Foo.

The same configuration can be made from code, using fluent configuration.

	new ContainerControlledLifetimeManager(), 
	new Interceptor(), 
			new InterceptionBehavior());

From this moment, all the calls of IFoo instances from Unity container will be intercepted by our custom interceptor (behavior).

There is also another method to implement this mechanism using attributes. Using attributes, you will need to implement ICallHandler interface to specify the custom behavior and create custom attributes that will be used to decorate the method that we want to intercept. Personally, I prefer the first version, using IInterceptionBehavior.


In this article we saw how easily we can add AOP functionality to a project that already uses Unity. Implementing this feature is very simple and flexible. We can very easily imagine more complex scenarios, combining IInterceptionBehavior and custom attributes.

Even if we don't have specific methods called by Unity before and after invocation, this can be very easily extended. I invite all of you to try Unity.




  • Accenture
  • BT Code Crafters
  • Accesa
  • Bosch
  • Betfair
  • MHP
  • BoatyardX
  • .msg systems
  • Yardi
  • P3 group
  • Ing Hubs
  • Colors in projects