Skip to content

marthijn/Sidio.ObjectPool

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

40 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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) {...}
}

About

Extensions and helper methods for Microsoft.Extensions.ObjectPool.

Topics

Resources

License

Stars

Watchers

Forks

Contributors 2

  •  
  •  

Languages