Skip to content

Instantly share code, notes, and snippets.

@wcoder
Last active November 19, 2019 13:53
Show Gist options
  • Save wcoder/44341a4ecafaaae861c4 to your computer and use it in GitHub Desktop.
Save wcoder/44341a4ecafaaae861c4 to your computer and use it in GitHub Desktop.
Static IoC container
public static class SimpleIoc
{
private static readonly ConcurrentDictionary<Type, object> _dependencyMap = new ConcurrentDictionary<Type, object>();
public static void Register<TName>(object instance)
{
_dependencyMap.TryAdd(typeof(TName), instance);
}
public static T Get<T>()
{
return (T) Get(typeof(T));
}
private static object Get(Type type)
{
_dependencyMap.TryGetValue(type, out object inst);
return inst;
}
}
@wcoder
Copy link
Author

wcoder commented Nov 19, 2019

New version:

// wcoder: https://gist.github.com/wcoder/44341a4ecafaaae861c4
public static class SimpleIoc
{
    private static readonly ConcurrentDictionary<Type, object> _dependencyMap = new ConcurrentDictionary<Type, object>();

    public static T Resolve<T>() => (T) Resolve(typeof(T));

    public static void Register<T>(T instance) => Register<T>((object) instance);

    private static void Register<T>(object value) => Register(typeof(T), value);

    private static void Register(Type type, object value) => _dependencyMap.TryAdd(type, value);

    private static object Resolve(Type type)
    {
        if (Get(type) is object fastInst)
        {
            return fastInst;
        }

        var ctor = type.GetConstructors()[0];
        var args = ctor.GetParameters();
        var deps = new object[args.Length];

        for (int i = 0; i < args.Length; i++)
        {
            deps[i] = Resolve(args[i].ParameterType);
        }

        return ctor.Invoke(deps);
    }

    private static object Get(Type type)
    {
        _dependencyMap.TryGetValue(type, out object inst);
        return inst;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment