Skip to content

Instantly share code, notes, and snippets.

@PatrickRainer
Last active October 22, 2020 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PatrickRainer/4b560df910db7b9b442585da6bd92cd4 to your computer and use it in GitHub Desktop.
Save PatrickRainer/4b560df910db7b9b442585da6bd92cd4 to your computer and use it in GitHub Desktop.
Minimal IOC
var container = new MinimalContainer();
container.Register<IWelcomer, Welcomer>();
container.Register<IWriter, ConsoleWriter>();
var welcomer = container.Create();
welcomer.SayHelloTo("World");
public interface IWelcomer {
void SayHelloTo(string name);
}
public class Welcomer : IWelcomer
{
private IWriter writer;
public Wey(IWriter writer) {
this.writer = writer;
}
public void SayHelloTo(string name)
{
writer.Write($"Hello {name}!");
}
}
public interface IWriter {
void Write(string s);
}
public class ConsoleWriter : IWriter
{
public void Write(string s)
{
Console.WriteLine(s);
}
}
public class MinimalContainer
{
private readonly Dictionary<Type, Type> types = new Dictionary<Type, Type>();
public void Register<TInterface, TImplementation>() where TImplementation : TInterface
{
types[typeof(TInterface)] = typeof(TImplementation);
}
public TInterface Create()
{
return (TInterface)Create(typeof(TInterface));
}
private object Create(Type type)
{
//Find a default constructor using reflection
var concreteType = types[type];
var defaultConstructor = concreteType.GetConstructors()[0];
//Verify if the default constructor requires params
var defaultParams = defaultCtor.GetParameters();
//Instantiate all constructor parameters using recursion
var parameters = defaultParams.Select(param => Create(param.ParameterType)).ToArray();
return defaultConstructor.Invoke(parameters);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment