Created
April 2, 2019 04:54
-
-
Save imzjy/8c1d42eff9820b779b2ee85b256e2116 to your computer and use it in GitHub Desktop.
Revisions
-
imzjy created this gist
Apr 2, 2019 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal 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>();