-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRegistry.cs
55 lines (50 loc) · 1.41 KB
/
Registry.cs
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
47
48
49
50
51
52
53
54
using System.Linq;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace RegistryOfSingletons
{
/// <summary>
/// Registry of all singletons
/// </summary>
public static class Registry
{
/// <summary>
/// The registry.
/// </summary>
private static readonly List<ISingleton> registry = new List<ISingleton>();
/// <summary>
/// For thread-safe operations
/// </summary>
private static readonly SmartLock smart = new SmartLock();
/// <summary>
/// You do not need to call it explicitly
/// Every Singleton must call it by itself
/// </summary>
/// <param name="singleton">instance</param>
public static void Register(ISingleton singleton)
{
if (singleton == null) return;
smart.Enter();
registry.Add(singleton);
smart.Exit();
}
/// <summary>
/// Get an instance or initialize it if doesn't exist
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static ISingleton InstanceOf<T>() where T : class, ISingleton
{
RuntimeHelpers.RunClassConstructor(typeof(T).TypeHandle);
smart.In();
var instance = registry.OfType<T>().FirstOrDefault();
smart.Out();
if (instance == null) {
smart.Enter();
instance = registry.OfType<T>().FirstOrDefault();
smart.Exit();
}
return instance;
}
}
}