Skip to content

[API Proposal]: ObjectPool.Create without new() constraint #62434

@ladeak

Description

@ladeak

Background and motivation

Today the existing ObjectPool.Create has new() constraint on the generic type parameter, because DefaultPooledObjectPolicy requires it.

Suggestion is a non-nullable IPooledObjectPolicy overload, so with a custom pooled object policy, we can create object pools for T does not have a default ctor (that would be the benefit of creating a custom IPooledObjectPolicy)

public static ObjectPool<T> Create<T>(IPooledObjectPolicy<T> policy) where T : class

API Proposal

namespace Microsoft.Extensions.ObjectPool;

public static class ObjectPool
{
    public static ObjectPool<T> Create<T>(IPooledObjectPolicy<T> policy) where T : class
}

API Usage

ObjectPool<MyType> pool = ObjectPool.Create<MyType>(new MyTypePolicy());

class MyType(int value) { }

class MyTypePolicy : IPooledObjectPolicy<MyType>
{
    public MyType Create() => new MyType(0);
    public bool Return(MyType obj)
    {
        return true;
    }
}

Alternative Designs

Instead of an overload (which might require changing and removing the parameter of the existing method), have a separate method name.

(I am happy to address the issue if there are no objections during the discussion.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-ready-for-reviewAPI is ready for formal API review - https://github.com/dotnet/apireviewsarea-networkingIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions