Unity IoC container: tips, tricks and dirty hacks

It took me two years to write this post. Each time I started writing it, it suffered from gradual and seemingly unavoidable feature creep: should I mention dependency inversion principle? What about SOLID principles in general? What about testability? The list goes on and on. But it was a recent interesting discussion with a friend about the use (and abuse) of dependency injection that prompted me to finally finish it.

I have been using Unity IoC container for a while now and in the process I have managed to ”abuse” it in every possible way so I hope this post covers some of the more advanced and intricate usage scenarios you may ever come across.

Trivial case

In case you have never used Unity before, the behaviour of the container is pretty trivial: call Register<T,TImpl>() on a number of types then make a call to Resolve<T> and with a bit of luck you will get a instance of it:

[TestFixture]
    class TrivialTests
    {
        [Test]
        public void TrivialOne()
        {
            var container = new UnityContainer();

            container.RegisterType<IBar, Bar>();

            var instance = container.Resolve<IBar>();

            Assert.NotNull(instance);
        }
    }

    internal class Bar : IBar {}
    internal interface IBar {}

Implementing a factory with Unityeven

Unity is not only able to resolve an implementation of a particular interface; it may also help in resolving dependencies when the type to be instantiated is known ( if it has not been registered with the container):

    [TestFixture]
    public class ObjectBuildupTest
    {
        [Test]
        public void ObjectBuildup()
        {
            var container = new UnityContainer();
            container.RegisterType<ISomeService, SomeService>();

            var anInstance = container.Resolve<ObjectWithDependencies>();

            Assert.NotNull(anInstance);
        }
    }

    public class ObjectWithDependencies
    {
        public ObjectWithDependencies(ISomeService  someService)
        {
            if (someService == null) throw new ArgumentNullException("someService");
        }
    }

    public interface ISomeService {}
    public class SomeService : ISomeService {}

As you can see from the code above, even though the type “ObjectWithDependencies” has not been registered with the container, Unity was able to correctly instantiate it and inject it with previously registered dependency. Such functionality may come very useful when implementing a factory: we know what we want to instantiate but not necessarily want to be bothered with instantiating all the dependencies. The following sample illustrates this approach.

    [TestFixture]
    public class FactoryTest
    {
        [Test]
        public void UnityBasedFactoryTest()
        {
            var container = new UnityContainer();

            container.RegisterType<ISomeService, SomeService>();
            container.RegisterType<ISomeFactory, SomeFactory>();

            var factory = container.Resolve<ISomeFactory>();

            Assert.NotNull(factory.ManufactureAnObject("A"));
        }
    }

    public interface ISomeFactory
    {
        ICommonInterface ManufactureAnObject(string anArgument);
    }

    public class SomeFactory : ISomeFactory
    {
        private readonly IUnityContainer _container;

        public SomeFactory(IUnityContainer container)
        {
            _container = container;
        }

        public ICommonInterface ManufactureAnObject(string anArgument)
        {
            switch(anArgument)
            {
                case "A":
                    return _container.Resolve<TypeA>();
                case "B":
                    return _container.Resolve<TypeB>();
                default:
                    throw new NotSupportedException();
            }
        }
    }

    public interface ICommonInterface {}

    public class TypeB : ICommonInterface
    {
        public TypeB(ISomeService someService)
        {            
        }
    }

    public class TypeA : ICommonInterface
    {
        public TypeA(ISomeService someService)
        {            
        }
    }

As you have probably noticed our factory requires an instance of IUnityContainer, luckily the container auto-registers itself, so whenever and instance of IUnityContainer is required, one will be injected without any fuss. Purists may frown upon direct use of the container, but in my opinion this is one of the very rare cases where it can be justified.

Multiple implementations of the same contract

The following example illustrates how to register multiple implementations of the same interface. Each registration is done with a particular key (quite a common feature among IoC containers) and then when resolving it we need to specify the key to get a particular implementation:

    [TestFixture]
    public class MultipleImplementationsTests
    {
        [Test]
        public void MultipleImplementations_ResolveCorrectly()
        {
            var container = new UnityContainer();
            container.RegisterType<IFooBar, SomeFooBar>("first");
            container.RegisterType<IFooBar, OtherFooBar>("second");

            Assert.NotNull(container.Resolve<IFooBar>("first"));
            Assert.NotNull(container.Resolve<IFooBar>("second"));
            Assert.Throws<ResolutionFailedException>(() => container.Resolve<IFooBar>());
        }
    }

    public interface IFooBar {}
    public class OtherFooBar : IFooBar {}
    public class SomeFooBar : IFooBar {}

This functionality can again be used to implement a factory of sorts but in general it is not that interesting until we get to the next point.

Building a composite

Having a multiple implementations of a particular contract registered with the container is the stepping stone to building a composite, as the following sample illustrates:

    [TestFixture]
    public class CompositeTests
    {
        [Test]
        public void BuildComposite()
        {
            var container = new UnityContainer();
            container.RegisterType<IFoo, SomeFoo>("first");
            container.RegisterType<IFoo, AnotherFoo>("second");
            container.RegisterType<IFoo, CompositeFoo>();

            var instanceOfFoo = container.Resolve<IFoo>();

            Assert.IsInstanceOf<CompositeFoo>(instanceOfFoo);
        }
    }

    public class CompositeFoo : IFoo
    {
        public CompositeFoo(IFoo[] others)
        {
            Debug.Assert(others != null);
            Debug.Assert(others.Any());
        }
    }

    public class AnotherFoo : IFoo {}
    public class SomeFoo : IFoo {}
    public interface IFoo {}

Composite in this case “consumes” an array of child objects and in a sense “sucks in” every implementation of IFoo registered with a key. This is an important aspect: if you were to register composite with a key, it would try to instantiate itself leading in immediately to StackOverflowException. The other interesting aspect is the fact that the composite requires an argument of type IChild[]. I am not sure about you but I personally find arrays very much 20th century and would rather have IEnumerable<IChild> injected, sadly Unity does not support it out of the box. There is however a workaround for it which I will share with you later.

Building chain of responsibility

Another interesting use case for naming your registrations is the implementation of Chain Of Responsibility pattern as the following sample illustrates:

    [TestFixture]
    class ChainOfResponsibilityTests
    {
        [Test]
        public void BuildChain()
        {
            var container = new UnityContainer();
            container.RegisterType<IChainLink, LastLink>("last");
            container.RegisterType<IChainLink, SecondLink>("second",
                                                           new InjectionConstructor(
                                                               new ResolvedParameter<IChainLink>("last")));
            container.RegisterType<IChainLink, FirstLink>(new InjectionConstructor(
                                                               new ResolvedParameter<IChainLink>("second")));

            var firstLink = container.Resolve<IChainLink>();

            Assert.IsInstanceOf<FirstLink>(firstLink);
        }
    }

    internal interface IChainLink {}

    internal class FirstLink : IChainLink
    {
        public FirstLink(IChainLink nextLink)
        {
            if (nextLink == null) throw new ArgumentNullException("nextLink");
        }
    }

    internal class SecondLink : IChainLink
    {
        public SecondLink(IChainLink nextLink)
        {
            if (nextLink == null) throw new ArgumentNullException("nextLink");
        }
    }

    internal class LastLink : IChainLink {}

 

In this case we need to resort to pointing each registered element of the chain to its predecessor which is achieved using ResolvedParameter<T>(name). This way we have full control as to what registration gets injected where. This may come helpful in cases where different implementations of the same contract are to be injected in different places.

Injecting the same object in multiple places in the object graph (semi-singleton)

Unity has a very interesting feature which allows the same object to be injected and shared in multiple places in the object graph. Let’s consider the following object diagram

:image

As you can see both the parent and the children contain references to an instance of Service. Standard behaviour of the IoC container is to inject new instance of the dependency into every object in the graph, this however may not be what we want:

image

In order to solve this conundrum Unity provides PerResolveLifetimeManager which within a single call to Resolve<T>() will create an instance of particular type and reuse it wherever required as the next sample illustrates:

    [TestFixture]
    public class PerResolutionLifetimeTests
    {
        [Test]
        public void Regiser_WithPerResolveLifetimeManager_ContainerInjectsSameInstance()
        {
            var container = new UnityContainer();
            container.RegisterType<IService, AService>(new PerResolveLifetimeManager());
            container.RegisterType<IParent, Parent>();
            container.RegisterType<IChild, Child>();

            var parent = container.Resolve<IParent>();

            Assert.AreSame(parent.Service, parent.Child.Service);
        }
    }

    public interface IService {}
    public class AService : IService {}
    public interface IChild
    {
        IService Service { get; set; }
    }

    public class Child : IChild
    {
        public IService Service { get; set; }

        public Child(IService service)
        {
            Service = service;
        }
    }

    public interface IParent
    {
        IChild Child { get; set; }
        IService Service { get; set; }
    }

    public class Parent : IParent
    {
        public IChild Child { get; set; }
        public IService Service { get; set; }

        public Parent(IChild child, IService service)
        {
            Child = child;
            Service = service;
        }
    }

Eternal problem: Chicken and Egg

Now there is an interesting chicken and egg problem which may seem to be impossible to solve using IoC container:

    
    public interface IEgg
    {
        IChicken Chicken { get; set; }
    }

    public interface IChicken
    {
        IEgg Egg { get; set; }
    }

    public class Chicken : IChicken
    {
        public IEgg Egg { get; set; }
    }

    public class Egg : IEgg
    {
        public Egg(IChicken chicken)
        {
            Chicken = chicken;
        }

        public IChicken Chicken
        {
            get;
            set;
        }
    }

As you can see we have a circular dependency going on here (Chicken “contains” an egg, while the egg points to its parent). This may seem to be a hopeless case but there is a solution to it: we need to combine property injection with PerResolveLifetimeManager:

[Test]
public void BuildObjectGraphWithCircularDependency()
{
    var container = new UnityContainer();

    container.RegisterType<IChicken, Chicken>(new PerResolveLifetimeManager(), new InjectionProperty("Egg"));
    container.RegisterType<IEgg, Egg>();

    var chicken = container.Resolve<IChicken>();

    Assert.AreSame(chicken, chicken.Egg.Chicken);
}

The magic above works as follows: container instantiates an instance of the Chicken class and then tries to resolve the Egg dependency. Egg in turn requires another instance of Chicken, luckily the Chicken class has been registered with PerResolveLifetimeManager which means it that instance of it can be reused in building the Egg. I think the case above is the only one I can think of where the use of property injection could be justified.

 

IoC and Interface segregation principle

There are some cases where a single type implements multiple contracts (interfaces). If you follow interface segregation principle this may lead to some troublesome cases:

[Test]
public void Resolve_ObjectDependantOnBaseInterface_ResolutionFails()
{
    var container = new UnityContainer();
    
    container.RegisterType<IDerived, Derived>();
    container.RegisterType<IDependsOnBase, DependsOnBase>();

    Assert.Throws<ResolutionFailedException>(() => container.Resolve<IDependsOnBase>());
}

public interface IBase { }
internal interface IDerived : IBase { }
internal class Derived : IDerived { }

public interface IDependsOnBase { }

public class DependsOnBase : IDependsOnBase
{
     public DependsOnBase(IBase dependency){}
}

As you can see from the code above, Derived implements IDerived which in turn is an instance of IBase. Inspite of that, resolution of DependsOnBase fails miserably. The reason is obviously the fact that there is no explicit implementation of IBase registered with the container. We could circumvent the problem by registering the Derived as type implementing the IBase interface. This approach would work but what if Derived implements more than one interface? There is however an easy way to work around the issue and this requires a hint to the container that instead of IBase it should search for an implementation of IDerived:

[Test]
public void Resolve_ObjectDependantOnBaseInterface_ResolutionSucceeds()
{
    var container = new UnityContainer();

    container.RegisterType<IDerived, Derived>();
    container.RegisterType<IDependsOnBase, DependsOnBase>(new InjectionConstructor(typeof(IDerived)));

    Assert.DoesNotThrow(() => container.Resolve<IDependsOnBase>());
}

This way btw it is the way to construct a composite using IEnumerable<> instead of an array as mentioned previously.

Overriding constructor parameters

The final set of Unity tricks deals with overriding constructor parameters. As you may remember we did this to a certain extent when registering individual elements of the chain of responsibility. There are two ways to do it: we can either instruct container at the time of registration to use specific instance of the parameters, or override parameter value at the time of resolution. Following sample illustrates both techniques.

[TestFixture]
public class ConstructorParameters
{
    [Test]
    public void OverridingCtorParams()
    {
        var container = new UnityContainer();
        container.RegisterType<SomeType>(new InjectionConstructor("Boo"));
        
        var firstInstance = container.Resolve<SomeType>();
        Assert.AreEqual("Boo", firstInstance.Message);

        var secondInstance = container.Resolve<SomeType>( new ParameterOverride("message", "Baa"));
        Assert.AreEqual("Baa", secondInstance.Message);
    }
}

public class SomeType
{
    public string Message { get; set; }

    public SomeType(string message)
    {
        Message = message;
    }
}
April 14 2012

Rx: Controlling frequency of events

One of the strengths of the Reactive Framework is the number of LINQ operators that ship with it.  This can also be a weakness though, as you wade through the list of sometimes-strangely named method looking for something in particular.  I recently wanted an operator that would have the following effect on an event stream:

regulate marble diagram

In other words, if events get raised too often then delay them so that the output stream has a defined maximum frequency of events over time. 

My first attempt at an implementation was to use the built-in Throttle operator, although I had a nagging feeling that this one doesn’t quite do what I expect it to.  My nagging sensation was proved correct … Throttle will throw away events if they are too frequent. In the end I resorted to building my own operator, which I call Regulate.  It’s a bit long, as it needs to address some threading considerations, but it’s not that difficult to follow:

using System;
using System.Reactive.Concurrency;
using System.Reactive.Linq;

namespace SharpFellows.RxUtils
{
    public static class ObservableExtensions
    {
        public static IObservable<T> Regulate<T>(this IObservable<T> observable, TimeSpan duration)
        {
            return Regulate(observable, duration, Scheduler.TaskPool);
        }

        public static IObservable<T> Regulate<T>(this IObservable<T> observable, TimeSpan duration, IScheduler scheduler)
        {
            var regulator = new ObservableRegulator<T>(duration, scheduler);

            return Observable.Create<T>(observer => observable.Subscribe(obj => regulator.ProcessItem(obj, observer)));
        }

        private class ObservableRegulator<T>
        {
            private DateTimeOffset _lastEntry = DateTimeOffset.MinValue;
            private readonly object _lastEntryLock = new object();

            private readonly TimeSpan _duration;
            private readonly IScheduler _scheduler;

            public ObservableRegulator(TimeSpan duration, IScheduler scheduler)
            {
                _duration = duration;
                _scheduler = scheduler;
            }

            public void ProcessItem(T val, IObserver<T> observer)
            {
                var canBroadcastNow = false;
                var nexEntryTime = DateTimeOffset.MaxValue;
                lock (_lastEntryLock)
                {
                    var now = DateTimeOffset.Now;
                    if (now.Subtract(_lastEntry) > _duration)
                    {
                        _lastEntry = now;
                        canBroadcastNow = true;
                    }
                    else
                    {
                        _lastEntry = _lastEntry.Add(_duration);
                        nexEntryTime = _lastEntry;
                    }
                }

                if (canBroadcastNow)
                {
                    observer.OnNext(val);
                }
                else
                {
                    _scheduler.Schedule(nexEntryTime, () => observer.OnNext(val));
                }

            }
        }
    }
}

The result is that you can specify the minimum time between events in the output stream (and optionally a scheduler):

return service.GetIrregularEvents()
              .Regulate(TimeSpan.FromSeconds(1));

FYI my use of this is to slowly drip feed items onto a data-bound UI.  Each new item triggers an animation and I don’t want 5 items simultaneously starting to animate.  Drop me an email or leave a comment if you find other uses for it!

Ninject: Auto-registration is changing in version 3

When I was using Ninject v2.2 I had this code to do my auto-registration:

using Ninject;
using Ninject.Extensions.Conventions;

public class CommonBootstrapper<TShell>
{
    private StandardKernel _kernel;

    protected override void Configure()
    {
        _kernel = new StandardKernel();
        _kernel.Scan(scanner =>
                         {
                             scanner.FromAssembliesInPath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
                             scanner.BindWithDefaultConventions();
                             scanner.InSingletonScope();
                         });
    }
}

For various reasons I upgraded to Ninject v3.0 RC3, and I found that there have been a number of breaking in Ninject.Extensions.Conventions.  My code now looks like this:

using Ninject;
using Ninject.Extensions.Conventions;

public class CommonBootstrapper<TShell>
{
    private StandardKernel _kernel;

    protected override void Configure()
    {
        _kernel = new StandardKernel();
        _kernel.Bind(scanner => scanner.FromAssembliesInPath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))
                                    .Select(IsServiceType)
                                    .BindToDefaultInterface()
                                    .Configure(binding => binding.InSingletonScope()));
    }

    private static bool IsServiceType(Type type)
    {
        return type.IsClass && type.GetInterfaces().Any(intface => intface.Name == "I" + type.Name);
    }
}

 

So there is a sweet new fluent interface, but more importantly you have to specify the exact conventions to use.  This makes it a lot easier to have non-standard convention, but it would be great if Ninject had the standard convention built in (IFoo binds to Foo).

For those who are into their own custom binding conventions (like Anthony), you will unfortunately find that the IBindingGenerator interface has changed.  Here is the v2.2 way of implementing a custom binding:

public class ViewModelConventions : IBindingGenerator
{
    public void Process(Type type, Func<IContext, object> scopeCallback, IKernel kernel)
    {
        if(type != null && kernel != null && !type.IsAbstract && type.IsClass && type.Name.EndsWith("Model"))
        {
            kernel.Bind(type)
                  .ToSelf()
                  .InScope(scopeCallback);
        }
    }
}

And here is the same class ported to Ninject v3.0 RC3.

public class ViewModelConventions : IBindingGenerator
{
    public IEnumerable<IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(Type type, IBindingRoot bindingRoot)
    {
        if (type != null && !type.IsAbstract && type.IsClass && type.Name.EndsWith("Model"))
        {
            yield return bindingRoot.Bind(type)
                                    .ToSelf();
        }
    }
}

It must be said, however, the goodness of the new fluent interface shown above means that I no longer need a custom binding generator – instead I can simply select the types I want and bind them directly in my bootstrapper.   I suspect that others will find the same!

March 20 2012

Getting values into a string

There are often times where it’s necessary to have some sort of template in a string, with placeholders that will be replaced with data-driven values at runtime.  Examples of this include email templates, mail merges and even integration scenarios.  Now there are many sophisticated and complex approaches to solving this problem, but here is a simple approach that works:

public static class StringExtensions
{
    public static string AddTokens(this string message, object tokenValues)
    {
        return tokenValues.GetType()
                .GetProperties()
                .Select(property => new
                            {
                                Key = property.Name,
                                Value = property.GetValue(tokenValues, new object[0]) as string
                            })
                .Aggregate(message, (current, token) => current.Replace("{" + token.Key + "}", token.Value));

    }

}

And to show you how to use it:

[Test]
public void ShouldReplaceTokens()
{
    var result = "1234{numbers}890".AddTokens(new { numbers = "567" });
    Assert.AreEqual("1234567890", result, "Tokens not added correctly");
}
January 16 2012
Newer Posts Older Posts