Skip to content

Instantly share code, notes, and snippets.

@davidwhitney
Created February 3, 2016 11:15
Show Gist options
  • Save davidwhitney/3637e430864ffcad20eb to your computer and use it in GitHub Desktop.
Save davidwhitney/3637e430864ffcad20eb to your computer and use it in GitHub Desktop.
Kata example for IoC
public class Container
{
private readonly Dictionary<Type, Type> _simpleMappings = new Dictionary<Type, Type>();
public T Create<T>()
{
return (T) Create(typeof (T));
}
public object Create(Type t)
{
var ctors = t.GetConstructors();
var biggestCtor = ctors.First();
var max = 0;
foreach (var ctor in ctors.Where(ctor => ctor.GetParameters().Length > max))
{
biggestCtor = ctor;
}
var dependencies = new List<object>();
foreach (var dep in biggestCtor.GetParameters())
{
var typeToCreate = SelectType(dep.ParameterType);
var depInstance = Create(typeToCreate);
dependencies.Add(depInstance);
}
return biggestCtor.Invoke(dependencies.ToArray());
}
private Type SelectType(Type parameterType)
{
if (!parameterType.IsInterface)
{
return parameterType;
}
var candidateImplementations = parameterType.Assembly.GetTypes()
.Where(x => !x.IsInterface && x.GetInterfaces().Contains(parameterType))
.ToList();
if (candidateImplementations.Count == 0)
{
throw new NotEnoughCandidatesException();
}
if (candidateImplementations.Count == 1)
{
return candidateImplementations.First();
}
if (_simpleMappings.ContainsKey(parameterType))
{
return _simpleMappings[parameterType];
}
throw new TooManyCandidatesException();
}
public Container For<TIface, TInstance>()
{
_simpleMappings.Add(typeof(TIface), typeof(TInstance));
return this;
}
}
public class TooManyCandidatesException : Exception
{
}
public class NotEnoughCandidatesException : Exception
{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment