Saturday, October 6, 2012

A Tiny Portable Inversion of Control Container for Multiple Windows Platforms

As part of the cross-platform example in my book, I built a tiny IOC container mainly to avoid having to reference and explain MEF, Unity, or any of the other choices. This is not a full-fledged container with tons of services like injection. It is simply an easy way to create things that depend on other things and manage their lifetime.

The "portable" part is evident in the targets. You can reference the exact same DLL from any Windows Phone, .NET Framework 4.x, Windows Store (Windows 8), or Silverlight 4+ project to use the container. That's it - completely portable, no recompiling necessary, and you now get to keep the same API on your view models when you're wiring dependencies (yes, I'm looking at providing a simple portable MVVM implementation too, but a portable Sterling will probably be my next focus since I get so many requests for it on Windows 8).

If you are dubious about what is possible across platforms, download the Chapter 9 source code from Windows8Applications.CodePlex.com (it's free, regardless of whether or not you get the book) and look at the Wintellog example. This is a full blown RSS feed reader implemented for both WPF and Windows Store (Windows 8) that uses most of the same code (even part of the networking stack). It includes a very basic version of the container that I used in the book.

The container is less than 200 lines of code. Many of the lines are there for design-by-contract checks and some thread-safety mechanisms to ensure unregistering and resolving from separate threads doesn't clobber the container.

It has a few features:

  • Uses a simple lambda expression to describe how to create implementations for types
  • Passes itself to the instance delegates so they can recursively resolve other references
  • Provides labels so you can segregate different definitions (or consider everything under a "label" as a different "container"
  • Allows you to unregister a definition (and register it as something different, though I can't imagine why you'd do that)
  • Allows you receive a shared or a non-shared instance (lifetime management
  • Allows you to destroy the shared instance and generate a new one
  • Provides a TryResolve to test and resolve in one operation

The use of it is fairly straightforward and can be inferred from the tests:

[TestInitialize]
public void TestInitialize()
{
    _target = new PortableIoc();
}

Register and resolve:

[TestMethod]
public void GivenTypeRegisteredWhenRequestedThenShouldReturnInstance()
{
    var expected = new SimpleBar();
    _target.Register<IBar>(ioc => expected);
    var actual = _target.Resolve<IBar>();
    Assert.AreSame(expected, actual, "Test failed: same instance was not returned.");
}

Test that you can resolve it:

[TestMethod]
public void GivenTypeRegisteredWhenCanResolveCalledThenShouldReturnTrue()
{
    _target.Register<IBar>(ioc => new SimpleBar());
    Assert.IsTrue(_target.CanResolve<IBar>(),
                    "Test failed: can resolve should return true when the type is registered.");
}

Try to resolve it:

[TestMethod]
public void GivenTypeIsNotRegisteredWhenTryResolveCalledThenShouldReturnFalse()
{
    IBar barInstance;
    var result = _target.TryResolve(out barInstance);
    Assert.IsNull(barInstance, "Test failed: bar instance should be null when type is not registered");
    Assert.IsFalse(result, "Test failed: result should be false when type is not registered.");
}

Generate a non-shared instance:

[TestMethod]
public void GivenTypeIsRegisteredWhenNewInstanceIsRequestedThenShouldReturnNewInstance()
{
    _target.Register<IBar>(ioc => new SimpleBar());
    var actual1 = _target.Resolve<IBar>();
    var actual2 = _target.Resolve<IBar>(true);
    Assert.AreNotSame(actual1, actual2, "Test failed: create new should not return the same shared instance.");
}

Use constructor injection:

target.Register<IBar>(ioc => new SimpleBar());            
_target.Register<IFoo>(ioc => new SimpleFoo(ioc.Resolve<IBar>()));

Or property injection:

target.Register<IBar>(ioc => new SimpleBar());            
_target.Register<IFoo>(ioc => new SimpleFoo { Bar = ioc.Resolve<IBar>() });

That's about it - you can grab the source and/or binary (sorry, no NuGet package yet) over at PortableIoC.CodePlex.com. Now let's get some work done on Sterling ...

Jeremy Likness