Created
April 2, 2019 04:54
-
-
Save imzjy/8c1d42eff9820b779b2ee85b256e2116 to your computer and use it in GitHub Desktop.
IoC, Implement the IoC within 33 lines of code, http://kenegozi.com/blog/2008/01/17/its-my-turn-to-build-an-ioc-container-in-15-minutes-and-33-lines
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
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