Skip to content

Instantly share code, notes, and snippets.

@Vengarioth
Created March 5, 2015 13:54
Show Gist options
  • Save Vengarioth/9fadc4e72f35567dced1 to your computer and use it in GitHub Desktop.
Save Vengarioth/9fadc4e72f35567dced1 to your computer and use it in GitHub Desktop.
dependency injector
public class Injector
{
private Dictionary<Type, object> injectables;
public Injector()
{
injectables = new Dictionary<Type, object>();
}
public void SetInjectable<Type>(object injectable)
{
injectables.Add(typeof(Type), injectable);
}
public Type CreateInstance<Type>() where Type : class
{
var type = typeof(Type);
var constructor = type.GetConstructors().First();
var parameters = constructor.GetParameters();
var arguments = new object[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
var parameter = parameters[i];
arguments[i] = injectables.ContainsKey(parameter.ParameterType) ? injectables[parameter.ParameterType] : null;
}
Type instance = (Type)Activator.CreateInstance(type, arguments);
return instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment