Untitled

 avatar
unknown
csharp
a month ago
2.0 kB
4
Indexable
using System;
using System.Collections.Generic;

public static class SingletonHub
{
    readonly static Log.Logger LOGGER = Log.SetTag(nameof(SingletonHub));
    readonly static Dictionary<Type, Func<object>> valueFactories = new();
    readonly static Dictionary<Type, object> instances = new();

    public static void Register(Func<object> valueFactory, Type type, bool overrideFactory = false, bool overrideValue = false)
    {
        if (!overrideValue && instances.ContainsKey(type))
        {
            LOGGER.Error($"Already has an object associated with key \"{type}\"");
            return;
        }

        if (overrideFactory)
        {
            valueFactories[type] = valueFactory;
            return;
        }

        valueFactories.Add(type, valueFactory);
    }

    public static void Register(object ins, Type type, bool overrideFactory = false, bool overrideValue = false)
    {
        if (valueFactories.ContainsKey(type))
        {
            if (!overrideFactory)
            {
                LOGGER.Error($"Already has an value factory associated with key \"{type}\"");
                return;
            }
            valueFactories.Remove(type);
        }

        if (overrideValue)
        {
            instances[type] = ins;
            return;
        }

        instances.Add(type, ins);
    }

    public static void Register<T>(Func<T> valueFactory, bool @override = false)
    {
        Register(valueFactory, typeof(T), @override);
    }

    public static void Register<T>(T ins, bool @override = false)
    {
        Register(ins, ins.GetType(), @override);
    }

    public static T Get<T>()
    {
        Type key = typeof(T);

        if (valueFactories.ContainsKey(key))
        {
            instances[key] = valueFactories[key].Invoke();
            valueFactories.Remove(key);
        }

        return (T)instances[key];
    }

    public static void Clear()
    {
        instances.Clear();
    }
}
Leave a Comment