Last active
October 22, 2020 13:02
-
-
Save PatrickRainer/4b560df910db7b9b442585da6bd92cd4 to your computer and use it in GitHub Desktop.
Minimal IOC
This file contains 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
var container = new MinimalContainer(); | |
container.Register<IWelcomer, Welcomer>(); | |
container.Register<IWriter, ConsoleWriter>(); | |
var welcomer = container.Create(); | |
welcomer.SayHelloTo("World"); |
This file contains 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 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); | |
} | |
} |
This file contains 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 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