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.
Recap
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.
Unity
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>(); 
//or
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.
  Configuration.InterceptionConfigurationExtension,
  Microsoft.Practices.Unity.Interception.Configuration"/>
…
<container>
  <extension type="Interception" />
  <register type="IFoo" mapTo="Foo">
    <interceptor type="InterfaceInterceptor" />
    <interceptionBehavior type="FooBehavior" />
  </register>
</container>
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.
Conclusion
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.    

Comments

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(...

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 http://go.microsoft.com/fwlink/?LinkId=260882 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.51 EF 6.0.2 VS2013 It see...

Navigating Cloud Strategy after Azure Central US Region Outage

 Looking back, July 19, 2024, was challenging for customers using Microsoft Azure or Windows machines. Two major outages affected customers using CrowdStrike Falcon or Microsoft Azure computation resources in the Central US. These two outages affected many people and put many businesses on pause for a few hours or even days. The overlap of these two issues was a nightmare for travellers. In addition to blue screens in the airport terminals, they could not get additional information from the airport website, airline personnel, or the support line because they were affected by the outage in the Central US region or the CrowdStrike outage.   But what happened in reality? A faulty CrowdStrike update affected Windows computers globally, from airports and healthcare to small businesses, affecting over 8.5m computers. Even if the Falson Sensor software defect was identified and a fix deployed shortly after, the recovery took longer. In parallel with CrowdStrike, Microsoft provi...