Soenneker.Utils.AsyncSingleton 4.0.748

Prefix Reserved
dotnet add package Soenneker.Utils.AsyncSingleton --version 4.0.748
                    
NuGet\Install-Package Soenneker.Utils.AsyncSingleton -Version 4.0.748
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Soenneker.Utils.AsyncSingleton" Version="4.0.748" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Soenneker.Utils.AsyncSingleton" Version="4.0.748" />
                    
Directory.Packages.props
<PackageReference Include="Soenneker.Utils.AsyncSingleton" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Soenneker.Utils.AsyncSingleton --version 4.0.748
                    
#r "nuget: Soenneker.Utils.AsyncSingleton, 4.0.748"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Soenneker.Utils.AsyncSingleton@4.0.748
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Soenneker.Utils.AsyncSingleton&version=4.0.748
                    
Install as a Cake Addin
#tool nuget:?package=Soenneker.Utils.AsyncSingleton&version=4.0.748
                    
Install as a Cake Tool

alternate text is missing from this package README image alternate text is missing from this package README image alternate text is missing from this package README image

alternate text is missing from this package README image Soenneker.Utils.AsyncSingleton

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.

Features

  • Lazy Initialization: The instance is created only upon the first call of Get(), GetAsync(), Init() or InitSync().
  • Thread-safe: Uses asynchronous locking for coordinated initialization in concurrent environments.
  • Multiple Initialization Patterns:
    • Sync and async initialization
    • With or without parameters (params object[])
    • With or without CancellationToken
  • Re-initialization Guard: Once the singleton is initialized (or has begun initializing), further initialization reconfigurations are disallowed.

Installation

dotnet add package Soenneker.Utils.AsyncSingleton

There are two different types: AsyncSingleton, and AsyncSingleton<T>:

AsyncSingleton<T>

Useful in scenarios where you need a result of the initialization. Get() is the primary method.

using Microsoft.Extensions.Logging;

public class MyService
{
    private readonly ILogger<MyService> _logger;
    private readonly AsyncSingleton<HttpClient> _asyncSingleton;

    public MyService(ILogger<MyService> logger)
    {
        _logger = logger;

        _asyncSingleton = new AsyncSingleton(async () =>
        {
            _logger.LogInformation("Initializing the singleton resource synchronously...");
            await Task.Delay(1000);

            return new HttpClient();
        });
    }

    public async ValueTask StartWork()
    {
        var httpClient = await _asyncSingleton.Get();

        // At this point the task has been run, guaranteed only once (no matter if this is called concurrently)

        var sameHttpClient = await _asyncSingleton.Get(); // This is the same instance of the httpClient above
    }
}

AsyncSingleton

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.

using Microsoft.Extensions.Logging;

public class MyService
{
    private readonly ILogger<MyService> _logger;
    private readonly AsyncSingleton _singleExecution;

    public MyService(ILogger<MyService> logger)
    {
        _logger = logger;

        _singleExecution = new AsyncSingleton(async () =>
        {
            _logger.LogInformation("Initializing the singleton resource ...");
            await Task.Delay(1000); // Simulates an async call

            return new object(); // This object is needed for AsyncSingleton to recognize that initialization has occurred
        });
    }

    public async ValueTask StartWork()
    {
        await _singleExecution.Init();

        // At this point the task has been run, guaranteed only once (no matter if this is called concurrently)

        await _singleExecution.Init(); // This will NOT execute the task, since it's already been called
    }
}

Tips:

  • If you need to cancel the initialization, pass a CancellationToken to the Init(), and Get() method. This will cancel any locking occurring during initialization.
  • 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.
  • Be careful about updating the underlying instance directly, as AsyncSingleton holds a reference to it, and will return those changes to further callers.
  • 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.
  • Try not to use an asynchronous initialization method, and then retrieve it synchronously. If you do so, AsyncSingleton will block to maintain thread-safety.
  • Using a synchronous initialization method with asynchronous retrieval will not block, and will still provide thread-safety.
  • Similarly, if the underlying instance is IAsyncDisposable, try to leverage AsyncSingleton.DisposeAsync(). Using AsyncSingleton.DisposeAsync() with an IDisposable underlying instance is fine.
Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (26)

Showing the top 5 NuGet packages that depend on Soenneker.Utils.AsyncSingleton:

Package Downloads
Soenneker.Utils.MemoryStream

An easy modern MemoryStream utility

Soenneker.Utils.Runtime

A collection of helpful runtime-based operations

Soenneker.Redis.Client

A utility library for Redis client accessibility

Soenneker.GitHub.Client

An async thread-safe singleton for Octokit's GitHubClient

Soenneker.ServiceBus.Admin

A utility library for Azure Service Bus Administration client accessibility

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
4.0.748 45,760 2/5/2026
4.0.747 30,984 1/22/2026
4.0.746 8,561 1/21/2026
4.0.745 11,062 1/20/2026
4.0.744 46,001 1/12/2026
4.0.743 41,725 1/7/2026
4.0.742 5,312 1/6/2026
4.0.741 2,732 1/6/2026
4.0.740 2,894 1/6/2026
4.0.739 1,972 1/6/2026
4.0.738 10,556 1/5/2026
4.0.737 102 1/5/2026
4.0.736 15,527 1/3/2026
4.0.735 4,672 1/2/2026
4.0.734 2,064 1/2/2026
4.0.733 111 1/2/2026
4.0.732 23,769 12/31/2025
4.0.731 5,604 12/31/2025
4.0.730 18,903 12/21/2025
4.0.729 2,976 12/21/2025
Loading failed