Skip to content

Instantly share code, notes, and snippets.

@stakx
Last active December 25, 2015 00:59
Show Gist options
  • Save stakx/6891514 to your computer and use it in GitHub Desktop.
Save stakx/6891514 to your computer and use it in GitHub Desktop.
The simplest, minimally useful non-auto-wiring Dependency Injection container (inspired by Autofac) that I could think of in about half a day's time.
using System;
using System.Collections.Generic;
public sealed class ContainerBuilder
{
public ContainerBuilder()
{
this.registrations = new Dictionary<RuntimeTypeHandle, object>();
}
private readonly Dictionary<RuntimeTypeHandle, object> registrations;
public void Register<T>(Func<ILifetimeScope, T> resolve)
{
registrations.Add(key: typeof(T).TypeHandle, value: resolve);
}
public void Register<T, TParam1>(Func<ILifetimeScope, TParam1, T> resolve)
{
registrations.Add(key: typeof(T).TypeHandle, value: resolve);
}
public ILifetimeScope Build()
{
return new LifetimeScope(registrations);
}
}
using System;
public interface ILifetimeScope : IDisposable
{
T Resolve<T>();
T Resolve<T, TParam1>(TParam1 arg1);
ILifetimeScope NewLifetimeScope();
}
using System;
using System.Collections.Generic;
internal sealed class LifetimeScope : ILifetimeScope
{
public LifetimeScope(Dictionary<RuntimeTypeHandle, object> registrations)
{
this.registrations = registrations;
this.trackedDisposables = new Stack<IDisposable>();
}
private readonly Dictionary<RuntimeTypeHandle, object> registrations;
private readonly Stack<IDisposable> trackedDisposables;
public T Resolve<T>()
{
var resolved = ((Func<ILifetimeScope, T>)registrations[typeof(T).TypeHandle])(this);
TrackIfDisposable(resolved);
return resolved;
}
public T Resolve<T, TParam1>(TParam1 arg1)
{
var resolved = ((Func<ILifetimeScope, TParam1, T>)registrations[typeof(T).TypeHandle])(this, arg1);
TrackIfDisposable(resolved);
return resolved;
}
private void TrackIfDisposable(object resolved)
{
var disposable = resolved as IDisposable;
if (disposable != null)
{
trackedDisposables.Push(disposable);
}
}
public ILifetimeScope NewLifetimeScope()
{
return new LifetimeScope(registrations);
}
public void Dispose()
{
while (trackedDisposables.Count > 0)
{
var disposable = trackedDisposables.Pop();
if (disposable != null)
{
disposable.Dispose();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment