Aliendreamer

dependencyContainer

Oct 22nd, 2018
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.94 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using SIS.Framework.Services.Contracts;
  6.  
  7. namespace SIS.Framework.Services
  8. {
  9.     public class DependencyContainer : IDependencyContainer
  10.     {
  11.         private readonly IDictionary<Type, Type> dependencyMap;
  12.  
  13.         public DependencyContainer(IDictionary<Type, Type> dependencyMap)
  14.         {
  15.             this.dependencyMap = dependencyMap;
  16.         }
  17.  
  18.         private Type this[Type key] =>
  19.             this.dependencyMap.ContainsKey(key)
  20.                 ? this.dependencyMap[key]
  21.                 : null;
  22.  
  23.         public void RegisterDependency<TSource, TDestination>()
  24.         {
  25.             this.dependencyMap[typeof(TSource)] = typeof(TDestination);
  26.         }
  27.  
  28.         public T CreateInstance<T>() =>
  29.             (T) CreateInstance(typeof(T));
  30.  
  31.         public object CreateInstance(Type type)
  32.         {
  33.             Type typeInstance = this[type] ?? type;
  34.  
  35.             if (typeInstance.IsInterface || typeInstance.IsAbstract)
  36.             {
  37.                 throw new InvalidOperationException(
  38.                     $"Type {typeInstance.FullName} cannot be instantiated. Abstract type and interfaces cannot be instantiated");
  39.             }
  40.  
  41.             ConstructorInfo constructor = typeInstance
  42.                 .GetConstructors()
  43.                 .OrderByDescending(c => c.GetParameters().Length)
  44.                 .First();
  45.  
  46.             ParameterInfo[] constructorParameters = constructor.GetParameters();
  47.  
  48.             object[] constructorParametersObjects = new object[constructorParameters.Length];
  49.  
  50.             for (int index = 0; index < constructorParameters.Length; index++)
  51.             {
  52.                 constructorParametersObjects[index] = this.CreateInstance(
  53.                     constructorParameters[index].ParameterType);
  54.             }
  55.  
  56.             return constructor.Invoke(constructorParametersObjects);
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment