Skip to main content

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;
Dependency.Register<IFoo>(
() => singleton ?? (singleton = new Foo()));

HTTP request-scoped instances would look something like:

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

A thread-local singleton would look something like:

public static class Local
{
  [ThreadStatic]
  internal IFoo instance;
}
...
Dependency.Register<IFoo>(
() => 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.

Comments

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.

Thanks,
Z-Bo
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.

Popular posts from this blog

Blue-eyed Islander Puzzle - an analysis

Many people find themselves stumped by the so-called Blue-Eyed Islanders puzzle . There is also much controversy over its supposed solution. I'm going to analyze the problem and the solution, and in the process, explain why the solution works. To begin, let's modify the problem slightly and say that there's only 1 blue-eyed islander. When the foreigner makes his pronouncement, the blue-eyed islander looks around and sees no other blue eyes, and being logical, correctly deduces that his own eyes must be blue in order for the foreigner's statement to make sense. The lone blue-eyed islander thus commits suicide the following day at noon. Now comes the tricky part, and the source of much confusion. Let's say there are 2 blue-eyed islanders, Mort and Bob. When the foreigner makes his pronouncement, Mort and Bob look around and see only each other. Mort and Bob thus both temporarily assume that the other will commit suicide the following day at noon. Imagine their chagrin...

The Chicken and the Egg - Redux

There is still considerable skepticism regarding my conclusion that the chicken comes first . Many of the objections are simply due to different interpretations of the question, interpretations which I consider unfaithful to the original purpose of the chicken-egg dilemma . Fundamentally, this question is supposed to represent a causality dilemma. When there is a causal dependency between any two objects, A and B, we can ask ourselves, "which came first, A or B?" An object C could have caused B, and thus triggered the recursive relation C→B→A→B→A... Of course, it could just as easily have been A that was caused first. To properly answer this question, we must reduce the abstract objects A and B to concrete objects and apply our scientific knowledge to ground the recursion. Using chickens and eggs as our objects, we have to precisely define what chickens and what eggs to consider. The question "which came first, chickens or any type of egg?" is not a causal dilemma a...

High-level constructs for low-level C: exception handling, RAII, sum types and pattern matching

There are numerous high-level abstractions available in other languages that simply make programming easier and less error prone. For instance, automatic memory management, pattern matching, exceptions, higher order functions, and so on. Each of these features enable the developer to reason about program behaviour at a higher level, and factor out common behaviour into separate but composable units. For fun, I've create a few small macro headers that enable some of these patterns in pure C. If anyone sees any portability issues, please let me know! libex: Exception Handling and RAII RAII in C is definitely possible via a well-known pattern used everywhere in the Linux kernel . It's a great way to organize code, but the program logic and finalization and error logic are not syntactically apparent. You have to interpret the surrounding context to identify the error conditions, and when and how finalization is triggered. To address this, I encapsulated this RAII pattern in a macro...