|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using MicroLibs.Moeda.Factories; |
| 4 | +using MicroLibs.Moeda.Qualifiers; |
| 5 | +using UnityEngine; |
| 6 | + |
| 7 | +namespace MicroLibs.Moeda |
| 8 | +{ |
| 9 | + public class MoedaApp |
| 10 | + { |
| 11 | + |
| 12 | + private readonly Dictionary<string, object> _dictionary = new Dictionary<string, object>(); |
| 13 | + private readonly Dictionary<Type, Module> _modules = new Dictionary<Type, Module>(); |
| 14 | + |
| 15 | + private readonly IScope _scope; |
| 16 | + |
| 17 | + public MoedaApp() |
| 18 | + { |
| 19 | + _scope = new Scope(this); |
| 20 | + } |
| 21 | + |
| 22 | + public void Load(Module module) |
| 23 | + { |
| 24 | + foreach (var value in module.GetDictionary()) |
| 25 | + { |
| 26 | + if (_dictionary.ContainsKey(value.Key)) |
| 27 | + { |
| 28 | + throw new Exception($"Duplicate object {value.Key}"); |
| 29 | + } |
| 30 | + |
| 31 | + _dictionary[value.Key] = value.Value; |
| 32 | + } |
| 33 | + |
| 34 | + _modules[module.GetType()] = module; |
| 35 | + } |
| 36 | + |
| 37 | + public void Unload<T>() where T: Module |
| 38 | + { |
| 39 | + var module = _modules[typeof(T)]; |
| 40 | + if (module == null) |
| 41 | + { |
| 42 | + Debug.Log($"Not found {typeof(T)}"); |
| 43 | + return; |
| 44 | + } |
| 45 | + foreach (var value in module.GetDictionary()) |
| 46 | + { |
| 47 | + _dictionary.Remove(value.Key); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + public TResult Inject<TResult>(IQualifier qualifier = null) { |
| 52 | + return Get<TResult>(qualifier); |
| 53 | + } |
| 54 | + |
| 55 | + public Lazy<TResult> InjectLazy<TResult>(IQualifier qualifier = null) { |
| 56 | + return new Lazy<TResult>(() => Get<TResult>(qualifier)); |
| 57 | + } |
| 58 | + |
| 59 | + internal TResult Get<TResult>(IQualifier qualifier = null) |
| 60 | + { |
| 61 | + var key = CreateKey(typeof(TResult), qualifier); |
| 62 | + return ((IFactory<TResult>)_dictionary[key]).Get(_scope); |
| 63 | + } |
| 64 | + |
| 65 | + private static string CreateKey(Type type, IQualifier qualifier) |
| 66 | + { |
| 67 | + return IndexKeyUtils.CreateKey(type, qualifier); |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments