.NET Zone is brought to you in partnership with:

Jeremy Likness was named Silverlight MVP of the Year in 2010. Now Senior Consultant and Technical Project Manager for Wintellect, LLC, he has spent the past decade building highly scalable web-based commercial solutions using the Microsoft technology stack. He has fifteen years of experience developing enterprise applications in vertical markets including insurance, health/wellness, supply chain management, and mobility. He is the creator of the popular MVVM framework Jounce and an open source Silverlight Isolated Storage Database System called Sterling. Likness speaks and blogs frequently on Silverlight, MEF, Prism, Team Foundation Server, and related Microsoft technologies. Jeremy is a DZone MVB and is not an employee of DZone and has posted 69 posts at DZone. You can read more from them at their website. View Full User Profile

A Tiny Portable Inversion of Control Container for Multiple Windows Platforms

10.06.2012
| 2283 views |
  • submit to reddit

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 fromWindows8Applications.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 atPortableIoC.CodePlex.com. Now let's get some work done on Sterling ...

Jeremy Likness

(c) 2011-2012 Jeremy Likness.
Published at DZone with permission of Jeremy Likness, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)