Edit

Generated WMI wrappers implement IDisposable

Starting in .NET 11, strongly typed WMI collection wrappers and their enumerators generated by ManagementClass.GetStronglyTypedClassCode implement IDisposable. Calling Dispose() releases the wrapped ManagementObjectCollection or ManagementObjectCollection.ManagementObjectEnumerator and its underlying COM-backed WMI resources deterministically.

Version introduced

.NET 11 RC 2

Previous behavior

The collection and enumerator types emitted by GetStronglyTypedClassCode did not implement IDisposable. A generated collection could not be used in a using statement, and consumers could not deterministically release the WMI resources held by its wrapped ManagementObjectCollection or enumerator.

// The generated ServiceCollection type did not implement IDisposable.
Service.ServiceCollection services = Service.GetInstances();

New behavior

The generated collection and enumerator types implement IDisposable. Consumers can dispose them to release the underlying WMI resources deterministically.

using Service.ServiceCollection services = Service.GetInstances();

foreach (Service item in services)
{
    // Use item.
}

Because the generated wrapper classes are non-sealed, adding IDisposable can affect code that derives from a generated wrapper and already declares a Dispose member or implements its own disposal pattern.

Type of breaking change

This change can affect source compatibility and is a behavioral change.

Reason for change

The generated wrappers hold COM-backed WMI resources. This change exposes disposal behavior already supported by the wrapped System.Management types so consumers can release those resources deterministically. The finalizer fallback of the wrapped types remains unchanged. For more information, see dotnet/runtime#132587.

Regenerate your strongly typed WMI wrappers with the updated generator. Then dispose generated collection and enumerator wrappers when they are no longer needed, preferably with using or using var.

If your code derives from a generated collection or enumerator wrapper and already defines a disposal pattern, review the generated type's new IDisposable implementation. Update the derived type to avoid conflicting Dispose members and to preserve disposal of both its own resources and the base wrapper's resources.

Affected APIs