Created
March 5, 2015 13:54
-
-
Save Vengarioth/9fadc4e72f35567dced1 to your computer and use it in GitHub Desktop.
dependency injector
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
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