Skip to content

Instantly share code, notes, and snippets.

@richardneililagan
Created September 27, 2013 07:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richardneililagan/6725122 to your computer and use it in GitHub Desktop.
Save richardneililagan/6725122 to your computer and use it in GitHub Desktop.
Poor man's IOC injector. Had to create a really quick injector for a quick story in a project. Worked like a charm.
class BasicInjector : IInjector
{
private Dictionary<Type, object> registry = new Dictionary<Type, object>();
public IInjector Register<TKey, TConcrete>()
where TConcrete : TKey
{
return Register<TKey>(() => Activator.CreateInstance<TConcrete>());
}
public IInjector Register<TKey>(Func<TKey> callback)
{
registry[typeof(TKey)] = callback;
return this;
}
public TKey Create<TKey>()
{
var tKey = typeof(TKey);
return registry.ContainsKey(tKey) ?
((Func<TKey>) registry[tKey])() :
default(TKey);
}
}
interface IInjector
{
IInjector Register<TKey, TConcrete> ()
where TConcrete : TKey;
IInjector Register<TKey>(Func<TKey> callback);
TKey Create<TKey>();
}
var injector = new BasicInjector();
// (1) register type keys
injector
.Register<ICar, Mazda>()
.Register<IDog, CockerSpaniel>()
;
// (1.a) or specify a more complex creation logic
injector
.Register<ICookie>(
() => {
var dough = new Dough();
var chips = new ChocoChips();
return new ChocolateChipCookie(dough, chips);
}
);
// 2. create a registered concrete type from another module by referencing the contract
var car = injector.Create<ICar>(); // will be a Mazda
var dog = injector.Create<IDog>(); // will be a CockerSpaniel
var cookie = injector.Create<ICookie>(); // will be a ChocolateChipCookie
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment