DI033

Container Will Not Dispose a Pre-Built Instance

A disposable instance handed to the container as an existing object — AddSingleton<TService>(new Thing()) or a descriptor carrying an implementation instance.

Info Default severity · Code fix: No

Why it matters

The container disposes only the instances it creates. An instance built by the caller is registered as-is, and disposing the provider does not touch it, so its file handles, sockets, or timers live until the process ends. The registration reads exactly like the type-registration form that *is* disposed, which is what makes it easy to miss.

README problem example

services.AddSingleton<IMetricsSink>(new MetricsSink());  // DI033: never disposed by the container

README better pattern

services.AddSingleton<IMetricsSink, MetricsSink>();

No — rewriting to a type registration changes construction, and disposing at shutdown is a lifecycle decision.

Guardrails

When DI033 stays silent

Non-disposable instances raise no ownership question, and factory registrations are exempt because the container *does* create and therefore dispose what a factory returns, as is a descriptor removed or replaced after it was added. Reported at Info: caller-owned disposal is a legitimate choice, just one worth making explicitly.

Repo sample extraction

Examples pulled from the sample app

Open full sample file

Sample app externally-owned instance note

        public static void Configure(IServiceCollection services)
        {
            // DI033: the container disposes only what it creates, so this sink's file handles
            // stay open until the caller disposes it.
            services.AddSingleton<IMetricsSink>(new MetricsSink());
        }

Sample app container-owned registration pattern

        public static void ConfigureGood(IServiceCollection services)
        {
            // Handing the type over makes the container the owner, disposal included.
            services.AddSingleton<IMetricsSink, MetricsSink>();
        }

Related guides

  • No problem-guide pages point here yet.

Nearby diagnostics

Other rules in this family

All 37 rules