diff --git a/src/Discord.Net.Commands/Dependencies/DependencyMap.cs b/src/Discord.Net.Commands/Dependencies/DependencyMap.cs index ba5995f26..7f489fda0 100644 --- a/src/Discord.Net.Commands/Dependencies/DependencyMap.cs +++ b/src/Discord.Net.Commands/Dependencies/DependencyMap.cs @@ -5,21 +5,29 @@ namespace Discord.Commands { public class DependencyMap : IDependencyMap { - private Dictionary map; + private Dictionary> map; public static DependencyMap Empty => new DependencyMap(); public DependencyMap() { - map = new Dictionary(); + map = new Dictionary>(); } - public void Add(T obj) + public void Add(T obj) where T : class + => AddFactory(() => obj); + public void AddTransient() where T : class, new() + => AddFactory(() => new T()); + public void AddTransient() where TKey : class + where TImpl : class, TKey, new() + => AddFactory(() => new TImpl()); + + public void AddFactory(Func factory) where T : class { var t = typeof(T); if (map.ContainsKey(t)) throw new InvalidOperationException($"The dependency map already contains \"{t.FullName}\""); - map.Add(t, obj); + map.Add(t, factory); } public T Get() @@ -51,7 +59,14 @@ namespace Discord.Commands } public bool TryGet(Type t, out object result) { - return map.TryGetValue(t, out result); + Func func; + if (map.TryGetValue(t, out func)) + { + result = func(); + return true; + } + result = null; + return false; } } } diff --git a/src/Discord.Net.Commands/Dependencies/IDependencyMap.cs b/src/Discord.Net.Commands/Dependencies/IDependencyMap.cs index 784a9bc56..aab94156b 100644 --- a/src/Discord.Net.Commands/Dependencies/IDependencyMap.cs +++ b/src/Discord.Net.Commands/Dependencies/IDependencyMap.cs @@ -4,7 +4,10 @@ namespace Discord.Commands { public interface IDependencyMap { - void Add(T obj); + void Add(T obj) where T : class; + void AddTransient() where T : class, new(); + void AddTransient() where TKey: class where TImpl : class, TKey, new(); + void AddFactory(Func factory) where T : class; T Get(); bool TryGet(out T result);