Saturday, July 21, 2012

Simple, Extensible IoC in C#

I just committed the core of a simple dependency injection container to a standalone assembly, Sasa.IoC. The interface is pretty straightforward:

public static class Dependency
  // static, type-indexed operations
  public static T Resolve<T>();
  public static void Register<T>(Func<T> create)
  public static void Register<TInterface, TRegistrant>()
            where TRegistrant : TInterface, new()

  // dynamic, runtime type operations
  public static object Resolve(Type registrant);
  public static void Register(Type publicInterface, Type registrant,
                              params Type[] dependencies)

If you were ever curious about IoC, the Dependency class is only about 100 lines of code. You can even skip the dynamic operations and it's only ~50 lines of code. The dynamic operations then just use reflection to invoke the typed operations.

Dependency uses static generic fields, so resolution is pretty much just a field access + invoking a delegate. The reason for this speed and simplicity is that it's very light on features, like lifetime management, instance sharing, etc. It's really just the core for dependency injection.

Still, it gets you far because the constructor delegate is entirely user-specified. You can actually build features like lifetime management on top of this core by supplying an appropriate delegate to Register<T>.

For instance, singleton dependencies would look like:

IFoo singleton = null;
() => singleton ?? (singleton = new Foo()));

HTTP request-scoped instances would look something like:

() => HttpContext.Current.Items["IFoo"]
   ?? (HttpContext.Current.Items["IFoo"] = new Foo()) as IFoo);

A thread-local singleton would look something like:

public static class Local
  internal IFoo instance;
() => Local.instance ?? (Local.instance = new Foo()));

Instance resolution with sharing is something like:

public static class Instances
  internal Dictionary<Type, object> cache =
       new Dictionary<Type, object>();
  internal Func<T> Memoize(Func<T> create)
    T value;
    return cache.TryGetValue(typeof(T), out value)
         ? value
         : cache[typeof(T)] = create();
Dependency.Register<IFoo>(Instances.Memoize(() => new Foo()));

This container doesn't handle cleanup though, so the thread-local example depends on the client to properly dispose of the thread-local IFoo instance. AutoFac IoC claims to handle disposal of all disposable instances, so I'm reading up a little on how that's done.

This approach seems to handle most common scenarios, but there are no doubt some limitations. Still, it's a good introduction for those curious about IoC implementation.


John Zabroski said...

Autofac emulates C++ RAII idiom as applied in Andrei Alexandrescu's book. In particular, the guarded constructor pattern. If you look in Guard.cs in the Autofac code, you will understand.


Sandro Magi said...

I'm actually considering a different direction.

AutoFac basically uses first-class containers which can lead to leaks. Using the current Sasa.IoC design with second-class containers, lifetime management is guaranteed leak-free.

It just doesn't play well with units of work that are processed by multiple threads, ie. ASP.NET HTTP pipeline. I can accommodate this by contexts that I can save/restore across threads, but I'm not entirely satisfied with that solution.

This is all for fun anyway, so we'll see what I come up with.