Created
September 15, 2018 07:13
-
-
Save oomusou/a29c204991b6f0cc8caee92f1a3a984d to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace ConsoleApp | |
{ | |
public static class MyServiceProvider | |
{ | |
private static readonly Dictionary<Type, Type> Store = new Dictionary<Type, Type>(); | |
public static T GetService<T>() | |
{ | |
if (Store.ContainsKey(typeof(T))) | |
{ | |
return (T) Compose(Store[typeof(T)]); | |
} | |
return default(T); | |
} | |
private static object Compose(Type type) | |
{ | |
var constructorInfo = | |
type.GetConstructors() | |
.FirstOrDefault( | |
constructor => | |
constructor | |
.GetParameters() | |
.All(parameter => Store | |
.Any(item => item.Key == parameter.ParameterType))); | |
if (constructorInfo == null) | |
{ | |
return Activator.CreateInstance(Store[type]); | |
} | |
var parameters = constructorInfo | |
.GetParameters() | |
.Select(parameter => Compose(Store[parameter.ParameterType])) | |
.ToArray(); | |
return constructorInfo.Invoke(parameters); | |
} | |
public static void Register<T>(Type type) | |
{ | |
Store[typeof(T)] = type; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment