Skip to main content

AOP and Unity

In one of posts I 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 post 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 write code in other modules that make the call itself to the logging system, using interception.
This functionality can be implement 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 developer 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 was full 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 develop expect 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 instances.
IUnityContainer myContainer = new UnityContainer(); 
myContainer.RegisterType<IFoo, Foo>(); 
myContainer. RegisterInstance<IFoo>( new Foo()); 

IFoo myFoo = myContainer.Resolve<Foo>();
When it is used with ASP.NET MVC, developers don’t need any more to manage the lifetime of resources used by Controllers, Unity manage this for them. The only think that they need to do is to register this resources and request them in the controller, like in the following example.
public class HomeController : Controller
  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 give us the possibility to inject our custom code before and after a call of our target object. This can be made only to the object that are register in Unity. We cannot alter the flow for object that are not in Unity container.
Unity give offer us this feature using a similar mechanism that is obtained 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 post we will see how easily 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 object that were created by Unity and registered in different container or object that were created in other places of our application. The only request from Unity is to have access to this object in one way or another.
How Unity can 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 mean that between the clients 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 this 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 inject 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 (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.
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’, that 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 expected to have two method, 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<Type> 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 specify for what type we want to make this interception. In the next example we will make this interception only for Foo type.
<sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.
  <extension type="Interception" />
  <register type="IFoo" mapTo="Foo">
    <interceptor type="InterfaceInterceptor" />
    <interceptionBehavior type="FooBehavior" />
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.
unity.RegisterType<IFoo, Foo>(
  new ContainerControlledLifetimeManager(),
  new Interceptor<InterfaceInterceptor>(),
      new InterceptionBehavior<FooBehavior>());
From this moment, all the call 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 a 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 use Unity. Implement this feature is very simple and flexible. We can imagine very easily more complex scenarios, combining IInterceptionBehavior and custom attributes.
Even if we don’t have specific method called by Unity before and after invocation, this can be extend very easily. I invite all of you to try Unity.    


Popular posts from this blog

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine:
threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration:

TeamCity.NET 4.51EF 6.0.2VS2013
It seems that there …

Entity Framework (EF) TransactionScope vs Database.BeginTransaction

In today blog post we will talk a little about a new feature that is available on EF6+ related to Transactions.
Until now, when we had to use transaction we used ‘TransactionScope’. It works great and I would say that is something that is now in our blood.
using (var scope = new TransactionScope(TransactionScopeOption.Required)) { using (SqlConnection conn = new SqlConnection("...")) { conn.Open(); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = conn; sqlCommand.CommandText = ... sqlCommand.ExecuteNonQuery(); ... } scope.Complete(); } Starting with EF6.0 we have a new way to work with transactions. The new approach is based on Database.BeginTransaction(), Database.Rollback(), Database.Commit(). Yes, no more TransactionScope.
In the followi…

GET call of REST API that contains '/'-slash character in the value of a parameter

Let’s assume that we have the following scenario: I have a public HTTP endpoint and I need to post some content using GET command. One of the parameters contains special characters like “\” and “/”. If the endpoint is an ApiController than you may have problems if you encode the parameter using the http encoder.
using (var httpClient = new HttpClient()) { httpClient.BaseAddress = baseUrl; Task<HttpResponseMessage> response = httpClient.GetAsync(string.Format("api/foo/{0}", "qwert/qwerqwer"))); response.Wait(); response.Result.EnsureSuccessStatusCode(); } One possible solution would be to encode the query parameter using UrlTokenEncode method of HttpServerUtility class and GetBytes method ofUTF8. In this way you would get the array of bytes of the parameter and encode them as a url token.
The following code show to you how you could write the encode and decode methods.