Skip to content

Instantly share code, notes, and snippets.

@imzjy
Created April 2, 2019 04:54
Show Gist options
  • Select an option

  • Save imzjy/8c1d42eff9820b779b2ee85b256e2116 to your computer and use it in GitHub Desktop.

Select an option

Save imzjy/8c1d42eff9820b779b2ee85b256e2116 to your computer and use it in GitHub Desktop.

Revisions

  1. imzjy created this gist Apr 2, 2019.
    50 changes: 50 additions & 0 deletions IoC.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    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>();