Skip to content

[API Proposal]: Add ServiceProviderOptions.ValidateDisposables to throw exception when transient service is diposable. #124581

@jlaanstra

Description

@jlaanstra

Background and motivation

Current default behavior allows for transient service registrations to implement IDisposable/IAsyncDisposable. As pointed out in other issues like #36461 that can cause memory leaks as a result instances being kept alive by the ServiceProvider until it gets disposed.

This proposal provides an alternative to #36461 and follows the pattern of ValidateScopes as introduced in aspnet/DependencyInjection#88

This proposal would work side by side with the latest proposal in #36461 as with that proposal an externally owned instance would not be captured.

API Proposal

namespace Microsoft.Extensions.DependencyInjection
{
    public class ServiceProviderOptions
    {
        /// <summary>
        /// <c>true</c> to perform check verifying that transient services would never get captured because they are disposable; otherwise <c>false</c>.
        /// </summary>
        public bool ValidateDisposables { get; set; }
    }
}

API Usage

new ServiceProviderOptions() { ValidateDisposables = true; }

Alternative Designs

Provide more extensive apis for validation as proposed by #119646

Risks

Low risk opt-in addition.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions