Skip to content

Instantly share code, notes, and snippets.

@oomusou
Created September 15, 2018 07:13
Show Gist options
  • Save oomusou/a29c204991b6f0cc8caee92f1a3a984d to your computer and use it in GitHub Desktop.
Save oomusou/a29c204991b6f0cc8caee92f1a3a984d to your computer and use it in GitHub Desktop.
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