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

How to check in AngularJS if a service was register or not

There are cases when you need to check in a service or a controller was register in AngularJS.
For example a valid use case is when you have the same implementation running on multiple application. In this case, you may want to intercept the HTTP provider and add a custom step there. This step don’t needs to run on all the application, only in the one where the service exist and register.
A solution for this case would be to have a flag in the configuration that specify this. In the core you would have an IF that would check the value of this flag.
Another solution is to check if a specific service was register in AngularJS or not. If the service was register that you would execute your own logic.
To check if a service was register or not in AngularJS container you need to call the ‘has’ method of ‘inhector’. It will return TRUE if the service was register.
if ($injector.has('httpInterceptorService')) { $httpProvider.interceptors.push('httpInterceptorService&#…

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.51EF 6.0.2VS2013
It seems that there …

Run native .NET application in Docker (.NET Framework 4.6.2)

Scope
The main scope of this post is to see how we can run a legacy application written in .NET Framework in Docker.

Context
First of all, let’s define what is a legacy application in our context. By a legacy application we understand an application that runs .NET Framework 3.5 or higher in a production environment where we don’t have any more the people or documentation that would help us to understand what is happening behind the scene.
In this scenarios, you might want to migrate the current solution from a standard environment to Docker. There are many advantages for such a migration, like:

Continuous DeploymentTestingIsolationSecurity at container levelVersioning ControlEnvironment Standardization
Until now, we didn’t had the possibility to run a .NET application in Docker. With .NET Core, there was support for .NET Core in Docker, but migration from a full .NET framework to .NET Core can be costly and even impossible. Not only because of lack of features, but also because once you…