|
3 | 3 | [](https://www.nuget.org/packages/Soenneker.Utils.AsyncSingleton/)
|
4 | 4 |
|
5 | 5 | #  Soenneker.Utils.AsyncSingleton
|
6 |
| -### An externally initializing singleton that uses double-check asynchronous locking, with optional async and sync disposal |
| 6 | + |
| 7 | +`AsyncSingleton` is a lightweight utility that provides lazy (and optionally asynchronous) initialization of an instance. It ensures that the instance is only created once, even in highly concurrent scenarios. It also offers both synchronous and asynchronous initialization methods while supporting a variety of initialization signatures. Additionally, `AsyncSingleton` implements both synchronous and asynchronous disposal. |
| 8 | + |
| 9 | +## Features |
| 10 | + |
| 11 | +- **Lazy Initialization**: The instance is created only upon the first call of `Get()`, `GetAsync()`, `Init()` or `InitSync()`. |
| 12 | +- **Thread-safe**: Uses asynchronous locking for coordinated initialization in concurrent environments. |
| 13 | +- **Multiple Initialization Patterns**: |
| 14 | + - Sync and async initialization |
| 15 | + - With or without parameters (`params object[]`) |
| 16 | + - With or without `CancellationToken` |
| 17 | +- **Re-initialization Guard**: Once the singleton is initialized (or has begun initializing), further initialization reconfigurations are disallowed. |
7 | 18 |
|
8 | 19 | ## Installation
|
9 | 20 |
|
10 | 21 | ```
|
11 | 22 | dotnet add package Soenneker.Utils.AsyncSingleton
|
12 | 23 | ```
|
13 | 24 |
|
14 |
| -## Example |
| 25 | +There are two different types: `AsyncSingleton`, and `AsyncSingleton<T>`: |
15 | 26 |
|
16 |
| -The example below is a long-living `HttpClient` implementation using `AsyncSingleton`. It avoids the additional overhead of `IHttpClientFactory`, and doesn't rely on short-lived clients. |
| 27 | +### `AsyncSingleton<T>` |
| 28 | +Useful in scenarios where you need a result of the initialization. `Get()` is the primary method. |
17 | 29 |
|
18 | 30 | ```csharp
|
19 |
| -public class HttpRequester : IDisposable, IAsyncDisposable |
| 31 | +using Microsoft.Extensions.Logging; |
| 32 | + |
| 33 | +public class MyService |
20 | 34 | {
|
21 |
| - private readonly AsyncSingleton<HttpClient> _client; |
| 35 | + private readonly ILogger<MyService> _logger; |
| 36 | + private readonly AsyncSingleton<HttpClient> _asyncSingleton; |
22 | 37 |
|
23 |
| - public HttpRequester() |
| 38 | + public MyService(ILogger<MyService> logger) |
24 | 39 | {
|
25 |
| - // This func will lazily execute once it's retrieved the first time. |
26 |
| - // Other threads calling this at the same moment will asynchronously wait, |
27 |
| - // and then utilize the HttpClient that was created from the first caller. |
28 |
| - _client = new AsyncSingleton<HttpClient>(() => |
| 40 | + _logger = logger; |
| 41 | + |
| 42 | + _asyncSingleton = new AsyncSingleton(async () => |
29 | 43 | {
|
30 |
| - var socketsHandler = new SocketsHttpHandler |
31 |
| - { |
32 |
| - PooledConnectionLifetime = TimeSpan.FromMinutes(10), |
33 |
| - MaxConnectionsPerServer = 10 |
34 |
| - }; |
| 44 | + _logger.LogInformation("Initializing the singleton resource synchronously..."); |
| 45 | + await Task.Delay(1000); |
35 | 46 |
|
36 |
| - return new HttpClient(socketsHandler); |
| 47 | + return new HttpClient(); |
37 | 48 | });
|
38 | 49 | }
|
39 | 50 |
|
40 |
| - public async ValueTask Get() |
| 51 | + public async ValueTask StartWork() |
41 | 52 | {
|
42 |
| - // retrieve the singleton async, thus not blocking the calling thread |
43 |
| - await (await _client.Get()).GetAsync("https://google.com"); |
| 53 | + var httpClient = await _asyncSingleton.Get(); |
| 54 | + |
| 55 | + // At this point the task has been run, guaranteed only once (no matter if this is called concurrently) |
| 56 | +
|
| 57 | + var sameHttpClient = await _asyncSingleton.Get(); // This is the same instance of the httpClient above |
44 | 58 | }
|
| 59 | +} |
| 60 | +``` |
45 | 61 |
|
46 |
| - // Disposal is not necessary for AsyncSingleton unless the type used is IDisposable/IAsyncDisposable |
47 |
| - public ValueTask DisposeAsync() |
| 62 | +### `AsyncSingleton` |
| 63 | +Useful in scenarios where you just need async single initialization, and you don't ever need to leverage an instance. `Init()` is the primary method. |
| 64 | + |
| 65 | +```csharp |
| 66 | +using Microsoft.Extensions.Logging; |
| 67 | + |
| 68 | +public class MyService |
| 69 | +{ |
| 70 | + private readonly ILogger<MyService> _logger; |
| 71 | + private readonly AsyncSingleton _singleExecution; |
| 72 | + |
| 73 | + public MyService(ILogger<MyService> logger) |
48 | 74 | {
|
49 |
| - GC.SuppressFinalize(this); |
| 75 | + _logger = logger; |
| 76 | + |
| 77 | + _singleExecution = new AsyncSingleton(async () => |
| 78 | + { |
| 79 | + _logger.LogInformation("Initializing the singleton resource ..."); |
| 80 | + await Task.Delay(1000); // Simulates an async call |
50 | 81 |
|
51 |
| - return _client.DisposeAsync(); |
| 82 | + return new object(); // This object is needed for AsyncSingleton to recognize that initialization has occurred |
| 83 | + }); |
52 | 84 | }
|
53 | 85 |
|
54 |
| - public void Dispose() |
| 86 | + public async ValueTask StartWork() |
55 | 87 | {
|
56 |
| - GC.SuppressFinalize(this); |
57 |
| - |
58 |
| - _client.Dispose(); |
| 88 | + await _singleExecution.Init(); |
| 89 | + |
| 90 | + // At this point the task has been run, guaranteed only once (no matter if this is called concurrently) |
| 91 | +
|
| 92 | + await _singleExecution.Init(); // This will NOT execute the task, since it's already been called |
59 | 93 | }
|
60 | 94 | }
|
61 |
| -``` |
| 95 | +``` |
| 96 | + |
| 97 | +Tips: |
| 98 | +- If you need to cancel the initialization, pass a `CancellationToken` to the `Init()`, and `Get()` method. This will cancel any locking occurring during initialization. |
| 99 | +- If you use a type of `AsyncSingleton` that implements `IDisposable` or `IAsyncDisposable`, be sure to dispose of the `AsyncSingleton` instance. This will dispose the underlying instance. |
| 100 | +- Be careful about updating the underlying instance directly, as `AsyncSingleton` holds a reference to it, and will return those changes to further callers. |
| 101 | +- `SetInitialization()` can be used to set the initialization function after the `AsyncSingleton` has been created. This can be useful in scenarios where the initialization function is not known at the time of creation. |
| 102 | +- Try not to use an asynchronous initialization method, and then retrieve it synchronously. If you do so, `AsyncSingleton` will block to maintain thread-safety. |
| 103 | +- Using a synchronous initialization method with asynchronous retrieval will not block, and will still provide thread-safety. |
| 104 | +- Similarly, if the underlying instance is `IAsyncDisposable`, try to leverage `AsyncSingleton.DisposeAsync()`. Using `AsyncSingleton.DisposeAsync()` with an `IDisposable` underlying instance is fine. |
0 commit comments