Categories: Blog

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

Recent Posts

8-Step AWS to Microsoft Azure Migration Strategy

Microsoft Azure and Amazon Web Services (AWS) are two of the most popular cloud platforms.…

6 days ago

How to Navigate Azure Governance

 Cloud management is difficult to do manually, especially if you work with multiple cloud…

2 weeks ago

Why Azure’s Scalability is Your Key to Business Growth & Efficiency

Azure’s scalable infrastructure is often cited as one of the primary reasons why it's the…

4 weeks ago

Unlocking the Power of AI in your Software Development Life Cycle (SDLC)

https://www.youtube.com/watch?v=wDzCN0d8SeA Watch our "Unlocking the Power of AI in your Software Development Life Cycle (SDLC)"…

1 month ago

The Role of FinOps in Accelerating Business Innovation

FinOps is a strategic approach to managing cloud costs. It combines financial management best practices…

1 month ago

Azure Kubernetes Security Best Practices

Using Kubernetes with Azure combines the power of Kubernetes container orchestration and the cloud capabilities…

2 months ago