Created
March 6, 2015 08:58
-
-
Save OzieWest/c65fd403f10b6c0f8a6e to your computer and use it in GitHub Desktop.
Own IoC Container
This file contains hidden or 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 MyContainer | |
| { | |
| private readonly Dictionary<Type, Type> _registrations; | |
| public MyContainer() | |
| { | |
| _registrations = new Dictionary<Type, Type>(); | |
| } | |
| public void Register<T, TS>() | |
| { | |
| _registrations.Add(typeof(T), typeof(TS)); | |
| } | |
| public T Get<T>() | |
| { | |
| return (T)GetObject(typeof(T)); | |
| } | |
| private object GetObject(Type parameterType) | |
| { | |
| if (!_registrations.ContainsKey(parameterType)) throw new Exception("Type not registered"); | |
| var concreteType = _registrations[parameterType]; | |
| var constructorParams = GetConstructorParams(concreteType); | |
| return Activator.CreateInstance(concreteType, constructorParams.ToArray()); | |
| } | |
| private IEnumerable<object> GetConstructorParams(Type concreteType) | |
| { | |
| var constructor = concreteType.GetConstructors().Single(); | |
| var cparams = constructor.GetParameters(); | |
| foreach (var parameterInfo in cparams) | |
| { | |
| yield return GetObject(parameterInfo.ParameterType); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment