แก้ไข

แชร์ผ่าน


ActivatorUtilities.CreateInstance requires non-null provider

The two ActivatorUtilities.CreateInstance methods now throw an ArgumentNullException exception if the provider parameter is null.

Version introduced

.NET 8 Preview 1

Previous behavior

A null value was allowed for the provider parameter. In some cases, the specified type was still created correctly.

New behavior

When provider is null, an ArgumentNullException exception is thrown.

Type of breaking change

This change is a behavioral change.

Reason for change

We fixed the parameter validation along with constructor-matching issues to align with the intended purpose of CreateInstance. The CreateInstance() methods have a non-nullable provider parameter, so it was generally expected that a null provider wasn't allowed.

Pass a non-null IServiceProvider for the provider argument. If the provider also implements IServiceProviderIsService, constructor arguments can be obtained through that.

Alternatively, if your scenario doesn't require dependency injection, since IServiceProvider is null, use Activator.CreateInstance instead.

Affected APIs

See also