Monday, March 11, 2013

Programming IoC Container

class Program
{
 static void Main(string[] args){
  Resolver resolver = new Resolver();
  resolver.Register<Shopper, Shopper>();
  resolver.Register<ICreditCard, MasterCard>();

  var shoper = resolver.Resolve<Shopper>();
  shopper.Charge();

  Console.Read();
 }
}
public class Resolver
{
 private Dictionary<Type, Type> dependencyMap = new Dictionary<Type, Type>();

 public T Resolve<T>()
 {
  return (T)Resolve(typeof(T));

  private object Resolve(Type typeToResolve)
  {
   Type resolvedType = null;
   try{
    resolvedType = dependencyMap[typeToResolve];
   }
   catch
   {
    throw new Exception(string.Format("Could not resolve type {0}", typeToResolve.FullName));
   }
 
   var firstConstructor = resolvedType.GetConstructors().First();
   var constructorParameters = firstConstructor.GetParameters();
   if(constructorParameters.Count() == 0)
    return Activator.CreateInstance(resolvedType);
  
   IList<object> parameters = new List<object>();
   foreach(var parameterToResolve in constructorParameters)
   {
    parameters.Add(Resolve(parameterToResolve.ParameterType);
   }
 
   return firstConstructor.Invoke(parameters.ToArray());
  }

  public void Register<TFrom, TTo>()
  {
   dependencyMap.Add(typeof(TFrom), typeof(TTo));
  }
 }

 public class Visa : ICreditCard
 {
  public string Charge()
  {
   return "Charging with the Visa!";
  }
 }

 public class MasterCard : ICreditCard
 {
  public string Charge()
  {
   return "Charging with the MasterCard!";
  }
 }

 public interface ICreditCard
 {
  string Charge();
 }
}

Reference: Pluralsight course on Inversion of Control by John Sonmez

No comments: