Skip to content

Instantly share code, notes, and snippets.

@imzjy
Created April 2, 2019 04:54
Show Gist options
  • Save imzjy/8c1d42eff9820b779b2ee85b256e2116 to your computer and use it in GitHub Desktop.
Save imzjy/8c1d42eff9820b779b2ee85b256e2116 to your computer and use it in GitHub Desktop.
static class IoC {
static readonly IDictionary<Type, Type> types = new Dictionary<Type, Type>();
public static void Register<TContract, TImplementation>() {
types[typeof(TContract)] = typeof(TImplementation);
}
public static T Resolve<T>() {
return (T)Resolve(typeof(T));
}
public static object Resolve(Type contract) {
Type implementation = types[contract];
ConstructorInfo constructor = implementation.GetConstructors()[0];
ParameterInfo[] constructorParameters = constructor.GetParameters();
if (constructorParameters.Length == 0) {
return Activator.CreateInstance(implementation);
}
List<object> parameters = new List<object>(constructorParameters.Length);
foreach (ParameterInfo parameterInfo in constructorParameters) {
parameters.Add(Resolve(parameterInfo.ParameterType));
}
return constructor.Invoke(parameters.ToArray());
}
}
// Plugin
public interface IFileSystemAdapter { }
public class FileSystemAdapter : IFileSystemAdapter { }
public interface IBuildDirectoryStructureService { }
public class BuildDirectoryStructureService : IBuildDirectoryStructureService{
IFileSystemAdapter fileSystemAdapter;
public BuildDirectoryStructureService(IFileSystemAdapter fileSystemAdapter) {
this.fileSystemAdapter = fileSystemAdapter;
}
}
//Usage
IoC.Register<IFileSystemAdapter, FileSystemAdapter>();
IoC.Register<IBuildDirectoryStructureService, BuildDirectoryStructureService>();
IBuildDirectoryStructureService service = IoC.Resolve<IBuildDirectoryStructureService>();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment