dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
34.84k stars 9.84k forks source link

Feature Request: Integrate ObjectPool into Dependency Injection #55367

Open grochoge opened 2 months ago

grochoge commented 2 months ago

Is there an existing issue for this?

Is your feature request related to a problem? Please describe the problem.

Right now if a service/etc wants to use an object from a Microsoft.Extensions.ObjectPool, it needs to know it's getting a pooled object.

There's also no way to customize service resolution and dispose behavior of the dependency injection machinery.

Describe the solution you'd like

Provide a way to automatically resolve a service from an object pool and return at the end of a scope (checking IResettable.TryReset if applicable). Perhaps something like a .AddPooled<IExampleService, ExampleService>( maxCount: 10 ) as an alternative to .AddScoped<IExampleService,ExampleService>().

Or at least provide customization hooks in the DI machinery so we can implement this ourselves.

Additional context

No response

amcasey commented 2 months ago

I suspect DI pooling has come up before. @halter73?

davidfowl commented 2 months ago

https://www.nuget.org/packages/Microsoft.Extensions.ObjectPool.DependencyInjection/

davidfowl commented 2 months ago

Source https://github.com/dotnet/extensions/tree/main/src/Libraries/Microsoft.Extensions.ObjectPool.DependencyInjection

amcasey commented 2 months ago

Thanks, @davidfowl! Good to go, @grochoge?

grochoge commented 1 month ago

Thanks, that is quite a bit better! But as far as I understand it still doesn't solve the issue of something needing to know it's getting an object from a pool.

Right now it seems like you'd need to wrap the pooled object in another class implementing the same interface and return the object to the pool inside the wrapper's .Dispose() method to get the behavior I'm thinking of. Ideally the DI machinery would provide hooks to allow doing something else (like returning to a pool) at the end of a scope rather than only being able to call .Dispose().

That certainly wouldn't be as performant (as you'd hold on to the object longer than needed) but conceptually seems like a cleaner separation.

davidfowl commented 1 month ago

Can you file an issue with the suggestions on how we can improve the APIs in that package? https://github.com/dotnet/extensions (hopefully not breaking)