-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServiceRegistry.cs
More file actions
83 lines (70 loc) · 2.5 KB
/
ServiceRegistry.cs
File metadata and controls
83 lines (70 loc) · 2.5 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using PatternKit.Generators.Singleton;
using System.Collections.Concurrent;
namespace PatternKit.Examples.SingletonGeneratorDemo;
/// <summary>
/// Simple service registry singleton demonstrating thread-safe lazy initialization.
/// In production, consider using a proper DI container like Microsoft.Extensions.DependencyInjection.
/// </summary>
[Singleton(Mode = SingletonMode.Lazy, Threading = SingletonThreading.ThreadSafe)]
public partial class ServiceRegistry
{
// Use Lazy<object> for thread-safe single-call factory semantics
private readonly ConcurrentDictionary<Type, Lazy<object>> _services = new();
private ServiceRegistry() { }
/// <summary>
/// Registers a service instance.
/// </summary>
public void Register<TService>(TService service) where TService : class
{
ArgumentNullException.ThrowIfNull(service);
_services[typeof(TService)] = new Lazy<object>(() => service);
}
/// <summary>
/// Registers a factory for lazy service creation.
/// The factory is guaranteed to be called at most once, even under concurrent access.
/// </summary>
public void RegisterFactory<TService>(Func<TService> factory) where TService : class
{
ArgumentNullException.ThrowIfNull(factory);
_services[typeof(TService)] = new Lazy<object>(() => factory());
}
/// <summary>
/// Resolves a registered service.
/// </summary>
/// <exception cref="InvalidOperationException">Service not registered.</exception>
public TService Resolve<TService>() where TService : class
{
var type = typeof(TService);
if (_services.TryGetValue(type, out var lazy))
{
return (TService)lazy.Value;
}
throw new InvalidOperationException($"Service {type.Name} is not registered.");
}
/// <summary>
/// Tries to resolve a service, returning null if not found.
/// </summary>
public TService? TryResolve<TService>() where TService : class
{
var type = typeof(TService);
if (_services.TryGetValue(type, out var lazy))
{
return (TService)lazy.Value;
}
return null;
}
/// <summary>
/// Checks if a service is registered.
/// </summary>
public bool IsRegistered<TService>() where TService : class
{
return _services.ContainsKey(typeof(TService));
}
/// <summary>
/// Clears all registrations. Useful for testing.
/// </summary>
public void Clear()
{
_services.Clear();
}
}