-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInstanceProvider.cs
More file actions
46 lines (40 loc) · 1.33 KB
/
InstanceProvider.cs
File metadata and controls
46 lines (40 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System.Collections.Concurrent;
namespace ResumableFunctions;
/// <summary>
/// Simple "dependency injection", just for prototyping
/// </summary>
public static class InstanceProvider
{
private static readonly ConcurrentDictionary<Type, Func<object>> factories = new();
private static readonly ConcurrentDictionary<Type, object> instances = new();
public static void Register<TType>(TType instance)
where TType : class
{
instances.TryAdd(typeof(TType), instance);
}
public static void Register<TType, TInstance>()
where TType : class
where TInstance : class, TType, new()
{
instances.TryAdd(typeof(TType), new TInstance());
}
public static void Register<TType>(Func<TType> factory)
where TType : class
{
factories.TryAdd(typeof(TType), factory);
}
public static TType Get<TType>()
where TType : class
{
if (instances.TryGetValue(typeof(TType), out var value) && value is TType instance)
{
return instance;
}
if (factories.TryRemove(typeof(TType), out var factory))
{
instances.TryAdd(typeof(TType), instance = (TType)factory());
return instance;
}
throw new Exception($"Instance of type {typeof(TType).Name} could not be found.");
}
}