Created
September 27, 2013 07:12
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface IInjector | |
{ | |
IInjector Register<TKey, TConcrete> () | |
where TConcrete : TKey; | |
IInjector Register<TKey>(Func<TKey> callback); | |
TKey Create<TKey>(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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