Skip to content

Instantly share code, notes, and snippets.

@rofr
Created March 17, 2014 15:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rofr/9601338 to your computer and use it in GitHub Desktop.
Save rofr/9601338 to your computer and use it in GitHub Desktop.
public class Args : Dictionary<string,object>{}
public class MyIoc
{
private Dictionary<Type, Dictionary<string, Func<Args, object>>> _registry
= new Dictionary<Type, Dictionary<string, Func<Args, object>>>();
public void Register<T>(Func<Args, T> factory, string name = "") where T : class
{
Type t = typeof(T);
if (!_registry.ContainsKey(t)) _registry[t] = new Dictionary<string, Func<Args, object>>();
_registry[t][name] = factory;
}
public T Resolve<T>(string name)
{
return Resolve<T>(null, name);
}
public T Resolve<T>(Args args = null, string name = "")
{
args = args ?? new Args();
Type t = typeof(T);
if (!_registry.ContainsKey(t)) throw new InvalidOperationException();
if (!_registry[t].ContainsKey(name)) throw new InvalidOperationException();
var factory = _registry[t][name];
return (T)factory.Invoke(args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment