/Sidio.ObjectPool

Extensions and helper methods for Microsoft.Extensions.ObjectPool.

Primary LanguageC#MIT LicenseMIT

Sidio.ObjectPool

This package provides an IObjectPoolService<T> interface and implementation that wraps an ObjectPool<T>.

Key features:

  • Simplify the usage of object pools
  • Integrate with dependency injection
  • Provide a Borrow method that returns an IDisposable wrapper around the pooled object, so it is automatically returned to the pool when disposed
  • Provide a default implementation for StringBuilder objects
  • Allow easy registration of custom object pools
  • Support .NET standard 2.0 and .NET 8 or higher applications

build NuGet Version Coverage Status

Usage (StringBuilder)

Service registration:

services.AddStringBuilderObjectPool();

Usage:

public class MyClass
{
    private readonly IObjectPoolService<StringBuilder> _stringBuilderPoolService;
    
    public MyClass(IObjectPoolService<StringBuilder> stringBuilderPoolService)
    {
        _stringBuilderPool = stringBuilderPoolService;
    }

    public void Example1()
    {
        var sb = _stringBuilderPoolService.Get();
        try
        {
            sb.Append("Hello, ");
            sb.Append("world!");
            Console.WriteLine(sb.ToString());
        }
        finally
        {
            _stringBuilderPoolService.Return(sb);
        }
    }
    
    public void Example2()
    {
        using var borrowedStringBuilder = _stringBuilderPoolService.Borrow();
        borrowedStringBuilder.Instance.Append("Hello, ");
        borrowedStringBuilder.Instance.Append("world!");
        Console.WriteLine(sb.Instance.ToString());
    }
}

Usage (custom types)

// Define a custom builder and object pool policy
public sealed class MyCustomPolicy : PooledObjectPolicy<MyCustomBuilder> {...}

// Register the object pool service
services.AddObjectPoolService((objectPoolProvider, serviceProvider) => objectPoolProvider.Create(new MyCustomPolicy()));

// Use the object pool service
public class MyClass
{
    public MyClass(IObjectPoolService<MyCustomBuilder> myCustomBuilderPoolService) {...}
}