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
Borrowmethod that returns anIDisposablewrapper around the pooled object, so it is automatically returned to the pool when disposed - Provide a default implementation for
StringBuilderobjects - Allow easy registration of custom object pools
- Support .NET standard 2.0 and .NET 8 or higher applications
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());
}
}// 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) {...}
}