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...

Easy Reverse Mode Automatic Differentiation in C#

Continuing from my last post on implementing forward-mode automatic differentiation (AD) using C# operator overloading , this is just a quick follow-up showing how easy reverse mode is to achieve, and why it's important. Why Reverse Mode Automatic Differentiation? As explained in the last post, the vector representation of forward-mode AD can compute the derivatives of all parameter simultaneously, but it does so with considerable space cost: each operation creates a vector computing the derivative of each parameter. So N parameters with M operations would allocation O(N*M) space. It turns out, this is unnecessary! Reverse mode AD allocates only O(N+M) space to compute the derivatives of N parameters across M operations. In general, forward mode AD is best suited to differentiating functions of type: R → R N That is, functions of 1 parameter that compute multiple outputs. Reverse mode AD is suited to the dual scenario: R N → R That is, functions of many parameters t...

Extensible, Statically Typed Pratt Parser in C#

I just completed a statically typed Pratt-style single-state extensible lexer+parser, otherwise known as a top-down operator precedence parser, for the Sasa library . The implementation is available in the Sasa.Parsing dll, under Sasa.Parsing.Pratt . Two simple arithmetic calculators are available in the unit tests . This implementation is novel in two ways: Aside from an alleged implementation in Ada , this is the only statically typed Pratt parser I'm aware of. Pratt parsers typically require a pre-tokenized input before parsing semantic tokens, but I've eliminated this step by using the symbol definitions to drive a longest-match priority-based lexer. Symbols by default match themselves, but you can optionally provide a scanning function used to match arbitrary string patterns. The symbol selected for the current position of the input is the symbol that matches the longest substring. If two symbols match equally, then the symbol with higher precedence is selected. The design...