Wednesday, September 22, 2010

ServiceLocator vs Dependency Injection

 

During the past weeks I have been trying to figure out if I should go with the DI(Dependency Injection) pattern or the SL (Service Locator) pattern.
I assume here that the reader know the difference between the two.

I have been using the SL pattern for years know and it has proved to be very valuable.

But guess what? Now they tell me that it is considered an anti-pattern. Have a look here

What really bugs me is that all DI examples including the example from Mark Seemann, are so naive and simple.

Sure if you have InterfaceA and InterfaceB, you can live with passing an implementation of InterfaceB to the constructor of  ClassA.

But graphs usually gets a little more complex that and if we follow the Soc principle, we might end up with a lot of dependencies in order for ClassA to actually do its magic.

The result of this is that the consumer of ClassA must manually wire up a dependency map before calling the constructor passing the root dependencies for ClassA.

To illustrate this we are going to use Mark’s example.

    public interface IOrderProcessor
    {
        void Process(Order order);
    }

    public class OrderProcessor
    {
        private IOrderValidator _orderValidator;
 
        public OrderProcessor(IOrderValidator orderValidator)
        {
            _orderValidator = orderValidator;
        }
    }

In order to use the order processor class we need to do the following:

OrderProcessor orderProcessor = new OrderProcessor(new OrderValidator());

That does not look to bad at all.

The OrderProcessor clearly states that it has a dependency upon an IOrderValidator implementation.

The question is… Do I really need to know about this dependencies? Let that rest for a minute while we expand the example.

Lets just quickly review the example from Mark.

public void Process(Order order)
{
    var validator = Locator.Resolve<IOrderValidator>();
    if (validator.Validate(order))
    {
        var collector = Locator.Resolve<IOrderCollector>();
        collector.Collect(order);
        var shipper = Locator.Resolve<IOrderShipper>();
        shipper.Ship(order);
    }
}

He only shows the SL variant of the example and I can’t help but wonder why?

Anyway, we see from the implementation that two more dependencies have been added to the OrderProcessor.

An interesting observation here is that the dependencies are only needed if the order is valid…….

But let’s stick with the DI approach and then we must add two more parameters to the OrderProcessor class.

    public class OrderProcessor
    {
        private IOrderValidator _orderValidator;
 
        public OrderProcessor(IOrderValidator orderValidator, IOrderCollector orderCollector, IOrderShipper orderShipper)
        {
            _orderValidator = orderValidator;
        }
    }

To use the OrderProcessor we now need to do this:

OrderProcessor orderProcessor = new OrderProcessor(new OrderValidator(), new OrderCollector(), new OrderShipper());

In addition to introducing a breaking change this also starts to look a little bit messy, wouldn’t you say?

We can also see here that we create OrderCollectior and OrderShipper instances regardless of the result from validator.Validate(order).

Lets take this even further by adding some logging capabilities.

All classes should have logging enabled and that means even more breaking changes.

ILogger logger = new Logger();
OrderProcessor orderProcessor = new OrderProcessor(new OrderValidator(logger), new OrderCollector(logger), new OrderShipper(logger));

I don’t know about you, but to me this starts to look a little complicated.

We might think of a solution where we let the OrderProcessor class create its own Logger, but that would be hiding a dependency, right?

Let’s get back to the question ..”Do I really need to know about this dependencies?”

I tell you what.. I just need to process orders and don’t really care that much how much magic is needed to actually do that.

If we review the actual contract (IOrderProcessor) involved to process orders it does not say anything about collectors and shippers.

So why should I care?

Do I really need to inject an IEngine instance before I can drive?

Yes, I would have to if I was the constructor of the car, but in this case I am just the consumer, see?

Remember Cole Trickle (Tom Cruise) from “Days of Thunder” .. (Yes, I’m actually that old)

"They told me to get in the car and drive and I could drive......but I don't know much about cars, o.k?!

What if the engine suddenly got equipped with a turbo?

So what? I DON’T CARE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! I just want to drive!!

To solve this nightmare of manual wiring we can use an Ioc container.

Given that the container is configured it will happily resolve all dependencies for us.

The configuration of the container remains pretty much the same whether we use DI or SL so that is not an argument.

I feel that DI is somewhat of a “all or nothing” solution.

In order for the container to resolve our dependencies we must use this pattern from the get go. Otherwise we are faced with manual dependency injection which I think we all can agree can become pretty messy.

Feel free to leave a comment, I would love to hear your opinion

Regards

Bernhard Richter

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Friday, July 16, 2010

Merging(ILMerge) assemblies targeting the .Net Runtime v4.0


Today I started the process of upgrading a lot of projects to Visual Studio 2010 and at the same time I set the target framework to 4.0.

Everything went relatively smooth except for the some projects where we have modified the msbuild file to include a call to ILMerge.

First it complained it could not resolve the reference to System.Core

Unresolved assembly reference not allowed: System.Core.

As it turned out I needed to tell ILMerge what framework version to use and where it is located.

Mike Barnet has mentioned this at Microsoft Research and the solution is to add a command line parameter like this: /targetplatform:v4,<path to your v4 framework directory> 

So where is the v4 framework directory?

It is located in “C:\Windows\Microsoft.NET\Framework\v4.0.30319” provided you have a default installation.

So I added the command line parameter like this

/targetplatform:v4“C:\Windows\Microsoft.NET\Framework\v4.0.30319”

Make sure that you don’t have a space between the version and the path. It actually caused a stack overflow on my machine :)

Anyway this worked very well and no more complaints about unresolved assemblies.

That was until I tried to merge an assembly that referenced the PresentationCore.dll.

Unresolved assembly reference..again.

What now?

After some investigation I found out that PresentationCore.dll is not located in “C:\Windows\Microsoft.NET\Framework\v4.0.30319”, but in a WPF subfolder.

Aha, that must be it.

The trick here is that the path to the framework should be this
“C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0”

This directory contains all the framework assemblies including PresentationCore.dll

So I changed the command line parameter to

/targetplatform:v4“C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0”

Suddenly all merging of assemblies succeeded.

Thursday, July 15, 2010

Adding mocking features to LinFu.Ioc

This post will show how to integrate a mocking library with the service container available in the LinFu framework.
We are going to kick this off by showing an example where the use of mock objects might be useful.

Imagine that we have two interfaces like the ones below.

public interface IServiceA
{
    int CalculateSomething();
}


public interface IServiceB
{
    int CalculateSomethingElse();
}

If we take a look at the implementation below we can see that ServiceA has a dependency to an IServiceB implementation.

public class ServiceA : IServiceA
{
    private IServiceB _serviceB;
    public ServiceA(IServiceB serviceB) 
    {
        _serviceB = serviceB;
    }

    public int CalculateSomething()
    {
        //Do something clever here....
        _serviceA.CalculateSomethingElse();
        //Do even more intelligent suff...
        return 42;
    }
}

It should be noted that dependency injection can be done in a variety of ways, but here it is done using constructor injection.

This means that when we request an instance of IServiceA the service container will also resolve the IServiceB implementation needed in the ServiceA constructor.

When writing our unit test for ServiceA, we might not be interested in whatever IServiceB does or even worse, it could represents a remote call not accessible to us when testing IServiceA. So we need to replace the default IServiceB implementation with a dummy implementation.

It is obvious how this can be done the manual way since this is such a naive example, but setting up mocking objects can be pretty complex if we need to install multiple objects.

It can also be the case that the dependency is created internally so that we do not have an easy way of replacing the implementation with a mocking instance.

So we need a way to tell the service container that whenever a request for a IServiceB instance is executed, it should return a mock instance.

It should also be noted here that I have used the Moq framework, but I guess this could very easily be adapted to other mocking frameworks as well.

Anyway, this is what I came up with:

ServiceContainer.StartMocking<IServiceB>();
var serviceA = ServiceContainer.GetService<IServiceA>();
var result = serviceA.CalculateSomething();
Assert.AreEqual(42,result);

We can see that creating a mock and configuring the service container is pretty simple.

ServiceContainer.StartMocking<IServiceB>();

This is all that we really need to do in order to replace the actual IServiceB implementation.

Buy what about those expectations you say?….

As it turns out the StartMocking method return a Mock<T> instance so that we can configure the mocking instance.

var mock =  ServiceContainer.StartMocking<IServiceB>();
mock.Expect(s => s.CalculateSomethingElse()).Returns(1);

So how is this actually possible? Well, we need to take a deeper look into LinFu.Ioc to answer that.

LinFu.Ioc actually offers several ways of hooking into the process of resolving service types and one is by implementing the IPreProcessor interface.

An IPreProcessor implementation allows us to inspects the service request and optionally replace its default factory.

/// <summary>
/// Inspects the requested service type and returns a mocked service instance if 
/// mocking has been enabled for the service type.     
/// </summary>
/// <seealso cref="ContainerExtensions"/>
public class MockPreprocessor : IPreProcessor
{
    private readonly IList<MockServiceInfo> _mockedServices;

    /// <summary>
    /// Initializes a new instance of the <see cref="MockPreprocessor"/>
    /// </summary>
    /// <param name="mockedServices"></param>
    public MockPreprocessor(IList<MockServiceInfo> mockedServices)
    {
        _mockedServices = mockedServices;
    }

    /// <summary>
    /// Inspects the service request and return a mocked service if available.
    /// </summary>        
    public void Preprocess(IServiceRequest request)
    {
        var serviceName = string.IsNullOrEmpty(request.ServiceName) ? null : request.ServiceName;
        
        var mockedServiceInfo =
            _mockedServices.Where(
                ms => ms.ServiceType == request.ServiceType && ms.ServiceName == serviceName).FirstOrDefault
                ();
        
        if (mockedServiceInfo != null)            
            request.ActualFactory = new FunctorFactory(r => mockedServiceInfo.Mock.Object);
    }
}

The MockPreProcessor takes a list of MockServiceInfo instances that basically tells the preprocessor what types for which to return mock objects.

/// <summary>
/// Contains details about the service type being mocked
/// </summary>
public class MockServiceInfo
{
    /// <summary>
    /// Gets or sets the <see cref="Mock"/> instance.
    /// </summary>
    public Mock Mock { get; set; }
    
    /// <summary>
    /// Gets or sets the service type being mocked.
    /// </summary>
    public Type ServiceType { get; set; }
            
    /// <summary>
    /// Gets or sets the name of the service being mocked.
    /// </summary>
    public string ServiceName { get; set; }
}

Now that we have all the basic infrastructure in place, we need some extensions methods that defines the API for the Moq integration.

/// <summary>
/// Contains extensions methods to integrate the Moq mocking library with the LinFu.Ioc framework.
/// </summary>
/// <seealso cref="http://code.google.com/p/moq/"/>
public static class ContainerExtensions
{
    private static readonly IList<MockServiceInfo> _mockedServices = new List<MockServiceInfo>();

    /// <summary>
    /// Creates a new <see cref="Mock{T}"/> instance and instructs the <see cref="IServiceContainer"/> 
    /// to return the <see cref="Mock.Object"/> instead of the actual service instance.
    /// </summary>
    /// <typeparam name="T">The type of service being mocked.</typeparam>
    /// <param name="serviceContainer">The <see cref="IServiceContainer"/> that will handle the mocked service request.</param>
    /// <returns><see cref="Mock{T}"/></returns>
    public static Mock<T> StartMocking<T>(this IServiceContainer serviceContainer) where T:class
    {            
        return StartMocking<T>(serviceContainer, null);            
    }

    /// <summary>
    /// Creates a new <see cref="Mock{T}"/> instance and instructs the <see cref="IServiceContainer"/> 
    /// to return the <see cref="Mock.Object"/> instead of the actual service instance.
    /// </summary>
    /// <typeparam name="T">The type of service being mocked.</typeparam>
    /// <param name="serviceContainer">The <see cref="IServiceContainer"/> responsible for creating the mocked service.</param>
    /// <param name="serviceName">The name of the service being mocked.</param>
    /// <returns><see cref="Mock{T}"/></returns>
    public static Mock<T> StartMocking<T>(this IServiceContainer serviceContainer, string serviceName) where T:class
    {
        InstallMockPreProcessor(serviceContainer);

        return CreateMock<T>(serviceName);
    }

    private static Mock<T> CreateMock<T>(string serviceName) where T:class
    {                        
        var mock = new Mock<T>();            
        var mockServiceInfo = new MockServiceInfo();
        mockServiceInfo.Mock = mock;
        mockServiceInfo.ServiceName = string.IsNullOrEmpty(serviceName) ? null : serviceName;
        mockServiceInfo.ServiceType = typeof (T);
        _mockedServices.Add(mockServiceInfo);
        return mock;
    }

    private static void InstallMockPreProcessor(IServiceContainer serviceContainer)
    {
        if (!serviceContainer.PreProcessors.Any(p => p.GetType() == typeof (MockPreprocessor)))
            serviceContainer.PreProcessors.Add(new MockPreprocessor(_mockedServices));
    }


    /// <summary>
    /// Stops mocking the requested service type.
    /// </summary>
    /// <typeparam name="T">The service type currently being mocked.</typeparam>
    /// <param name="serviceContainer">The <see cref="IServiceContainer"/> currenly responsible for creating the mocked service.</param>        
    public static void StopMocking<T>(this IServiceContainer serviceContainer) where T : class
    {
        StopMocking<T>(serviceContainer, null);
    }


    /// <summary>
    /// Stops mocking the requested service type.
    /// </summary>
    /// <typeparam name="T">The service type currently being mocked.</typeparam>
    /// <param name="serviceContainer">The <see cref="IServiceContainer"/> currenly responsible for creating the mocked service.</param>
    /// <param name="serviceName">The name of the service curretly being mocked.</param>
    public static void StopMocking<T>(this IServiceContainer serviceContainer, string serviceName) where T : class
    {
        serviceName = string.IsNullOrEmpty(serviceName) ? null : serviceName;
        var mockServiceInfo =
            _mockedServices.Where(ms => ms.ServiceType == typeof (T) && ms.ServiceName == serviceName).
                FirstOrDefault();

        if (mockServiceInfo != null)
            _mockedServices.Remove(mockServiceInfo);
    }

    /// <summary>
    /// Stops mocking all services.
    /// </summary>
    /// <param name="serviceContainer">The <see cref="IServiceContainer"/> responsible for creating mocked services.</param>
    public static void StopMocking(this IServiceContainer serviceContainer)
    {
        _mockedServices.Clear();
    }

}

There are also methods for actually stop mocking types in the service container and that might be useful if you have different needs in various tests targeting the same service container instance.

Download the source here.

 

Happy mocking!!!

 

 

 

 

 

 

 
  

Friday, April 30, 2010

Bringing new aspects to life using the LinFu framework


Today we are going to see some examples of Aspect Oriented Programming(AOP) and see how that can help us perform tasks that we otherwise might be forced to hard wire into our source code. 

AOP can be thought of as a way of bringing new aspects/behaviors/features into our application without changing the original implementation.

The title for this article may be a little over the top, but if you're new to AOP, it may bring some new aspects to your life as a developer :)

We are going take a look at some examples and finish up by creating a simple data access library.

But first things first

Inversion Of Control

Before we delve into the world of AOP I thought it might be a good idea to talk a little about Inversion Of Control (IOC).

Inversion Of Control (also referred to as Dependency Injection) as a way of separating the creation of objects from their actual use.

I think maybe the term "Inversion of Control" is enough to scare people away from this type of software development. If you are already in control, why would you invert it as the term implies?. What does that even mean?

Lets illustrate this with an example. Imagine that we have some calculator class that can add two numbers and return the result.


public
 class Calculator

{

    public int Add(int value1, int value2)

    {

        return value1 + value2;

    }

}

Using this class from the client code would look something like the following:

Calculator calculator = new Calculator();

var result = calculator.Add(2, 2);


While the code certainly works, it creates a direct dependency between the client code and the concrete Calculator class.
Let's try to make things a little better by creating an interface for the Calculator class to implement.

public interface ICalculator

{

    int Add(int value1, int value2);

}

 

public class Calculator : ICalculator

{

    public int Add(int value1, int value2)

    {

        return value1 + value2;

    }

}


Now the client code would change to something like:

ICalculator calculator = new Calculator();

var result = calculator.Add(2, 2);


Now this is getting better by the minute, but we are still faced with the problem of how to create a Calculator instance without the dependency problem.
I can almost hear some of you wondering "Why don't he just use the Abstract Factory Pattern?"
And for those of you going "Abstract what?", lets go ahead and implement it for our naive little example.

First we need an abstract factory

public interface ICalculatorFactory

{

    ICalculator CreateCalculator();

}


Then we need a concrete factory

public
 class CalculatorFactory : ICalculatorFactory
{
    public ICalculator CreateCalculator()
    {
        return new Calculator();
    }
}

As for the abstract product and concrete product, we already have those defined (ICalculator and Calculator).
The client code would now be changed to this:

ICalculatorFactory factory = new CalculatorFactory();

ICalculator calculator =  factory.CreateCalculator();                      

var result = calculator.Add(2, 2);


Given that the CalculatorFactory class and the Calculator class is not contained in the same assembly, the client code does not longer need to know anything about the concrete Calculator class.

While this is a very naive example and does not fully show the power of the Abstract Factory Pattern, we still see that we need to do quite some work to create the abstractions we want.

In the world of IOC, we don’t really deal with abstract factories and all the plumbing needed.
We just rely on the service container to resolve our dependencies.

Using a service container we could instead just write:

serviceContainer.GetService<ICalculator>();

We have no factory classes to support this so how can the service container figure out the concrete type?

Introducing LinFu.Ioc

Several years ago I came across this article written by my good friend and colleague, Philip Laureano. It was this very article that really got me started on creating loosely coupled applications in the first place.

There are a vast of Ioc frameworks available including the relatively new Unity framework from Microsoft, but I have yet to see something that is so simple to use and understand.
As you will learn throughout this articles, I am not a big fan of XML configuration (or any configuration for that matter) and as you will see, configuring the LinFu service container takes only one single line of code.

serviceContainer.LoadFrom(AppDomain.CurrentDomain.BaseDirectory, "*.dll");

Now lets see what we need to do in order to have the container return an ICalculator instance.

[Implements(typeof(ICalculator))]

public class Calculator : ICalculator

{

    public int Add(int value1, int value2)

    {

        return value1 + value2;

    }

}


Notice the difference from our previous example?
The ImplementsAttribute tells the container that this is the concrete implementation to create when a request for an ICalculator instance is made.
I can only speak for my self here, but I find this a lot easier than learning how to configure this using some kind of XML format.
Besides from being incredible easy to use, it is also very very flexible.
If your not already familiar with LinFu.Ioc, I strongly recommend reading more about it here.

A word about project structure

When starting out to create a new library I always create at least three sub projects for the library. If we take the sample code for this article, this is how the solution is set up.

AopDemo Contains the interfaces
AopDemo.Implementation Contains the implementation of the interfaces
AopDemo.Tests Contains the unit tests

The thing to notice here is that the client code, here represented by the unit tests, will never reference the assembly containing the implementation.

In fact, the implementation will never be referenced by any other assembly.

Aspect Oriented Programming

AOP can be thought of as a way of bringing new aspects/behaviors/features into our application without changing the original implementation.

Given the previous example, say that we wanted to do a Console.WriteLine every time we add two numbers. How could we do that without touching the actual Calculator class?

There are actually two ways of doing that and that is the "easy way" using a proxy and the rather more complicated approach that involves IL injection.

Both methods have their advantages and disadvantages, but the proxy approach most certainly have the advantage of being simple to implement.

So what we are going to to here is implement a proxy that adds our new aspect (Console.WriteLine) to the ICalculator implementation.


The Proxy

Now lets start off by looking at what a proxy actually is.
A proxy is something that sits between the caller and the actual implementation.

As we can see the proxy also implements the ICalculator interface and hence the caller is still obliviously happy since it does not really care about the actual implementation as long as it implements the expected interface. 
In addition to forwarding method call from the caller to the actual implementation (Calculator), the proxy object also offers interception of the calls being made. 

So what we need here is an interceptor that we can use to implement our simple logging mechanism.

Introducing LinFu.Proxy

The LinFu framework not only ships with an excellent IOC container, but it also contains a very flexible proxy library.

One thing that I really like about this library, is that it is built using the IOC principle/pattern which makes it easy if we need to handle corner case scenarios.

That is, however not within the scope of this article so we are going to get back to creating the interceptor we need to perform logging in the calculator.

public class CalculatorInterceptor : IInterceptor

{              

    public object Intercept(IInvocationInfo info)

    {

        Console.WriteLine("The Add method has been invoked");

        return info.TargetMethod.Invoke(info.Target, info.Arguments);          

    }

}


The Intercept method is called whenever the client code calls a method through the proxy object.

The question now remains...How do we tell the service container to return a Calculator Proxy instead of the actual Calculator?

Again the flexibility in LinFu opens up for several ways of doing that and here is an very elegant approach I am almost certain you have never seen before.

Let's change the CalculatorInterceptor into the following:


[Intercepts(typeof(ICalculator))]

public class CalculatorInterceptor : IInterceptor

{              

    public object Intercept(IInvocationInfo info)

    {

        Console.WriteLine("The Add method has been invoked");

        return info.TargetMethod.Invoke(info.Target, info.Arguments);          

    }

}


Notice the difference? Take a look at the Intercepts attribute.
This attribute actually tells the service container to create a proxy object and forward method calls to this class.

Believe it or not, we have actually added a new aspect to the calculator with just 9 lines of code (Counting the curly brackets).

How's that for easy of use and flexibility?

The only requirement for the CalculatorInterceptor is that it is located on disc when the container is configured.

This means that we can add tracing to an already deployed application just by doing a simple XCopy.

This is getting so good that I think we should spend a little time to take this to the next level.

Say now that we wanted to allow for multiple logging targets and not just a simple Console.WriteLine.

We could of course add each logging target to the CalculatorInterceptor, but lets make this a little more exciting.

We start of by abstracting the actual logging out of the CalculatorInterceptor by creating an ILogger interface.

public interface ILogger

{

    void Log(string message);

}


Then we are going to ever so slightly alter the CalculatorInterceptor class.

[Intercepts(typeof(ICalculator))]

public class CalculatorInterceptor : IInterceptor, IInitialize

{

    private IEnumerable<ILogger> _loggers;

 

    public object Intercept(IInvocationInfo info)

    {

        foreach (var logger in _loggers)

        {

            logger.Log("The Add method has been invoked");

        }

        return info.TargetMethod.Invoke(info.Target, info.Arguments);          

    }

 

    public void Initialize(IServiceContainer source)

    {

        _loggers = source.GetServices<ILogger>();

    }

}


What’s new here is that we have implemented the IInitialize interface that is used by the service container to expose itself to the services instances it creates.

We then use the container to retrieve all implementations of the ILogger interface and handles the logging of to each instance.

And as for the Console.WriteLine, it has been moved to an ILogger implementation.

[Implements(typeof(ILogger))]

public class ConsoleLogger : ILogger

{

    public void Log(string message)

    {

        Console.WriteLine(message);

    }

}


The beauty of this is that we can now create as many ILogger implementations as we want and they will all be invoked when the Add method is invoked.

Pretty cool, wouldn't you say?

From naiveness towards the real world

While this so far has shown how flexible the LinFu framerwork is, it still remains a fact that the calculator example is pretty naive.

Let's pick it up a notch and create something useful. Why don't we create a DBMS independent data access library with profiling capabilities?
That might sound like a daunting task, but thanks to LinFu, this practically becomes a breeze.

Let's boil this data access paradigm down to what is it that we really need?
We need some object that we can use to execute sql, right?

For me it sounds like a IDbCommand implementation should fit the picture just perfectly.
How do we get a IDbCommand implementation? Simple, we just hand it off to the container like this:

var dbCommand = ServiceContainer.GetService<IDbCommand>();

But wait a minute, how does the container know what implementation of IDbCommand to create?

The answer is that is does not so we need to teach the container how to create an IDbCommand instance.

The code below shows a rudimentary factory implementation.

[Factory(typeof(IDbCommand))]

public class DbCommandFactory : IFactory<IDbCommand>

{       

    public IDbCommand CreateInstance(IFactoryRequest request)

    {

        var connectionStringSettings = GetConnectionStringSetting(request.ServiceName);

        var providerFactory = CreateProviderFactory(connectionStringSettings);

        var connection = providerFactory.CreateConnection();

        connection.ConnectionString = connectionStringSettings.ConnectionString;

        connection.Open();

        return connection.CreateCommand();           

    }

 

    private static DbProviderFactory CreateProviderFactory(

        ConnectionStringSettings connectionStringSettings)

    {

        return DbProviderFactories

            .GetFactory(connectionStringSettings.ProviderName);

    }  

 

    private static ConnectionStringSettings GetConnectionStringSetting(string connectionName)

    {

        if (String.IsNullOrEmpty(connectionName))

            return ConfigurationManager.ConnectionStrings

                .Cast<ConnectionStringSettings>().Last();

        return

            ConfigurationManager.ConnectionStrings

            .Cast<ConnectionStringSettings>().Where(

                c => c.Name.EndsWith(connectionName)).FirstOrDefault();

    }

}

Luckily for us, most of the abstractions has already been done for us. We just need to hook up with the appropriate DbProviderFactory and we are pretty much good to go.

We can now go ahead and configure our connection in app/web config and that's all we really need to do. We can now get a ready and willing IDbCommand instance by doing:

var dbCommand = ServiceContainer.GetService<IDbCommand>();

Sweet, but didn't I promise profiling capabilities? Okay, let's spend another five minutes.

We start off by creating an interface for the profilers

public interface IDbProfiler

{

    void BeforeExecute(IDbCommand dbCommand, MethodInfo methodInfo, object[] arguments);

    void AfterExecute(IDbCommand dbCommand, MethodInfo methodInfo, object[] arguments);

}

Next we need an interceptor that intercepts calls made to the actual DbCommand.

[Intercepts(typeof(IDbCommand))]

public class DbCommandInterceptor : IInterceptor, IInitialize

{

    private IEnumerable<IDbProfiler> _profilers;

 

    public object Intercept(IInvocationInfo info)

    {

        foreach (var dbProfiler in _profilers)

            dbProfiler.BeforeExecute((IDbCommand) info.Target,

                info.TargetMethod, info.Arguments);

 

        var returnValue =  info.TargetMethod.Invoke(info.Target, info.Arguments);

 

        foreach (var dbProfiler in _profilers)

            dbProfiler.AfterExecute((IDbCommand) info.Target,

                info.TargetMethod, info.Arguments);

 

        return returnValue;

    }

 

    public void Initialize(IServiceContainer source)

    {

        _profilers = source.GetServices<IDbProfiler>().ToList();

    }

}

As we can see we are doing much of the same that with did with in the calculator  example.

Now lets finish this off by creating a sample IDbCommand profiler.

[Implements(typeof(IDbProfiler))]

public class ConsoleDbProfiler : IDbProfiler

{

    private readonly Stopwatch _stopwatch = new Stopwatch();

 

    public void BeforeExecute(IDbCommand dbCommand, MethodInfo methodInfo, object[] arguments)

    {           

        if (ShouldProfile(methodInfo))

        {

            _stopwatch.Reset();

            _stopwatch.Start();

        }

    }

 

    public void AfterExecute(IDbCommand dbCommand, MethodInfo methodInfo, object[] arguments)

    {

        if (ShouldProfile(methodInfo))

        {           

            _stopwatch.Stop();               

            Console.WriteLine(string.Format("The command '{0}' executed in {1} milliseconds"

                , dbCommand.CommandText, _stopwatch.ElapsedMilliseconds));

 

        }

    }

 

    private static bool ShouldProfile(MethodInfo methodInfo)

    {

        var methodName = methodInfo.Name;

        return (methodName == "ExecuteReader"

                || methodName == "ExecuteNonQuery"

                || methodName == "ExecuteScalar");

 

    }

}

The fact is that we use a similar approach at work at it has proven invaluable to us when it comes to hunting down long running queries.

The following code shows the execution of the query:

var dbCommand = ServiceContainer.GetService<IDbCommand>();

dbCommand.CommandText = "SELECT * FROM Orders";

var reader = dbCommand.ExecuteReader(CommandBehavior.CloseConnection);

And in our debug output window we can now observe the following:

The command 'SELECT * FROM Orders' executed in 116 milliseconds

And that my friends, is how we add new aspects to even a sealed type. (Yes, the SqlDbCommand is actually sealed)

Please note that all exception handling has been omitted for the sake of brevity.

Conclusion

As we have seen, using the LinFu framework, taking the shift towards AOP is ridiculously simple to overcome.

We have seen how we can add new aspects to existing classes with out touching the original code and even implemented a simple data access library.

We can also draw the conclusion that AOP helps serving the Separation of Concerns principle as we don’t clutter our classes with aspects that is beyond their initial intent.

So the next time you create a new class, make sure you do so by implementing an interface.

You never know when new requirements (aspects) arrive.

Enjoy!!!!

Wednesday, February 3, 2010

Tracking changes made to POCO objects


Imagine that we retrieve a list of POCO (Plain Old CLR Objects) and we find our self in need to track changes made to those objects.

To illustrate this we use a very simple example like the Customer class:

    public class Customer

    {

        public string CustomerID { get; set; }

    }

Standard CLR properties has no built-in support for interception so the preferred way of doing this is to implement the INotifyPropertyChanged interface.

This interface allows us to notify subscribers that the property has changed and its widely used when two-way data binding is required.

If we bind, say a textbox to a property that does not support change notification, we end up with a situation where changes made to the textbox is automatically reflected in the property, but not the other way around.

The data binding mechanism (WinForms and WPF), relies heavily on this interface to do its magic.

The example below shows our modified Customer object with support for change notification.

    public class Customer : INotifyPropertyChanged

    {

        private string _customerId;

 

        public string CustomerID

        {

            get { return _customerId; }

            set

            {

                _customerId = value;

                OnPropertyChanged("CustomerID");

            }

        }

 

        protected void OnPropertyChanged(string propertyName)

        {

            if (PropertyChanged != null)

                PropertyChanged(this,new PropertyChangedEventArgs(propertyName));

        }

 

        public event PropertyChangedEventHandler PropertyChanged;

    }

Although the interface is quite easy to implement it also results in a lot of tidious code for us to write. Every property setter need that call to OnPropertyChanged passing along the property name.

Sure we could create a base class that implemented this interface and by that simplify it to some extent, but that takes our classes away from the POCO principle.

AOP to the rescue

I'd say that we let our objects remain POCO objects and implement the INotifyPropertyChanged interface at runtime instead.

You might wonder how that can be done and there are actually two ways of achieving that.

We can find a lot of  documentation on Aspect Oriented Programming that is more or less difficult to understand, but let us try to sum it up in one sentence.

AOP is about adding new aspects to an object without the object ever knowing about it.

The Aspect in our case is implementing the INotifyPropertyChanged interface so that changes made to the Customer object are intercepted by the caller.

And we want to do this at runtime.

There are actually two ways of doing that and we can either use a proxy to the actual customer object or we can use IL injection to modify the customer object so that it implements what we need, in this case the INotifyPropertyChanged interface.

Lets start of simple with the proxy approach.

The Proxy

A proxy is an object that sits between the caller and the actual target object.

The proxy class will at least implement the target interface, but can also implement additional interfaces which is the key to our solution.

Creating a proxy object can be done in two different ways:

  • Create a proxy by sub classing the target object.
    This requires all members to be declared as virtual members so that they can be overridden in the proxy type.
  • Create a proxy that implements the same interface that the actual target object does.
    This requires the members to be declared in an interface implemented by the target object.

We are going to stick to the second approach here as we will see later, provides us with a little more flexibility.

So we extract the interface from our Customer object.

    public interface ICustomer

    {

        string CustomerID { get; set; }

    }

 

    public class Customer : ICustomer

    {

        public string CustomerID { get; set; }

    }

Now the customer implements a contract that also can be implemented by our customer proxy type.

As mentioned before the proxy class can implement additional interfaces and that means that the proxy type can implement the INotifyPropertyChanged interface.

The figure below shows that the textbox now binds to the CustomerProxy and since it implements INotifyPropertyChanged, a two-way communication now exists between the
CustomerProxy and the textbox (client).

Proxy

So any changes to the CustomerID exposed by the CustomerProxy will now be reflected in the textbox.

And this actually brings us to the downside of the proxy approach.
For all this to work, changes to the CustomerID (that we want to be reflected in the textbox), must be made through the CustomerProxy.

If we have some logic inside the Customer object that internally updates the CustomerID property, the changes are not reflected in the textbox.

Why? Simply because we are not invoking the Customer proxy that is resposible for the change notification.

In the case that the proxied objects contains logic that may present a problem if the code actually updates the properties.

IL Injection.

This approach takes you far beyond the topics you might encounter in your average "Teach yourself C# in 21 days" book.

What we are talking about here is modifying the Customer class in such a way that it implements the INotifyPropertyChanged interface.

The modification is done by injecting the IL code that normally would be the result of implementing the interface in the first place.

The injection can be done at runtime or after the assembly has been compiled.

We are going concentrate on runtime modification here and that involves the following steps.

1. Load the assembly from disc (not into the application domain)

2. Modify the assembly (IL injection)

3. Save the assembly back to disc or load it as an byte array into the application domain without touching the original assembly.

There is only one library that I know of that actually allows us to do this, and that is Mono.Cecil.

This is a very powerful library that pretty much lets us do whatever we want with our assembly.

An interesting problem with this approach is how to get access to the target assembly before it is loaded into the application domain.

As we already know, once an assembly is loaded into the application domain, there is not much we can do about that. It can not be unloaded nor modified.

So we need to catch it BEFORE Fusion resolves the assembly and loads it into the application domain.

Again this presents us with two possible solutions.

  • Make sure that Fusion is unable to resolve the assembly and handle the AppDomain.AssemblyResolve event.
    This can be done by placing the assembly in a subfolder
  • Make sure that the assembly is not referenced directly
    Load the assembly our self and make the necessary changes to it before it gets loaded into the application domain.        

IMHO, depending on Fusion being unable to locate the assembly seems somewhat “hacky”.

If the assembly is not referenced by the application itself, it can be loaded dynamically by an Inversion of Control container and we can hook into the load process and do our magic before the container starts to register services from that assembly.

There is also another that presents a challenge when doing IL injection and that is how to enable debugging in our modified/weaved assemblies.

If we modify the IL, the symbol information (pdb) also needs to be updated. If we don’t handle that properly, we will not be able to set a breakpoint inside a class that at runtime has been modified.

Mono.Cecil provides some support here and from what I have tested so far, we should be able to actually debug weaved assemblies.

Conclusion

As we can see there are many decisions that needs to be made as to how we are going to inject new behavior into our objects and I would say it depends a lot of what kind of behavior we want to add.

Initially I wanted to create some kind of state/change tracker that hooks up the PropertyChanged event and keeps track of changes made to an object graph.

My gut feeling here is to go with the Proxy implementation as it allows us to keep everything i C# (No IL injection) and it allows proxies to be installed in a lazy fashion as we navigate down the object graph.

It is also somewhat simpler to add support for new interfaces, for example the IDataErrorInfo interface if we should want to give some visual feedback when validation errors occur.