aspnet / Announcements

Subscribe to this repo to be notified about major changes in ASP.NET Core and Entity Framework Core
Other
1.66k stars 80 forks source link

[Breaking change]: Handling of middleware types with multiple constructors #514

Open amcasey opened 1 month ago

amcasey commented 1 month ago

Description

Formerly, when a middleware type with multiple satisfiable constructors was instantiated from the dependency injection container, the one with the most parameters would be used. Now that only happens if the dependency injection container implements IServiceProviderIsService.

Version

.NET 9 RC 1

Previous behavior

Formerly, the first constructor was preferred (when both were satisfied) because it has more parameters.

public class CookiePolicyMiddleware
{
    public CookiePolicyMiddleware(RequestDelegate next, IOptions<CookiePolicyOptions> options, ILoggerFactory factory)
    {
        // Omitted for brevity
    }

    public CookiePolicyMiddleware(RequestDelegate next, IOptions<CookiePolicyOptions> options)
    {
        // Omitted for brevity
    }
}

New behavior

Now, neither constructor is preferred and construction fails with an error like

System.InvalidOperationException: 'Multiple constructors accepting all given argument types have been found in type 'Microsoft.AspNetCore.CookiePolicy.CookiePolicyMiddleware'. There should only be one applicable constructor.'

Type of breaking change

Reason for change

The activation mechanism was changed to help support keyed dependency injection.

Recommended action

If this happens and you can't upgrade to a dependency injection container that implements IServiceProviderIsService, you can add ActivatorUtilitiesConstructorAttribute to the preferred constructor of the affected middleware type.

Affected APIs

This is known to cause errors when instantiating Microsoft.AspNetCore.CookiePolicy.CookiePolicyMiddleware with Autofac.Extensions.DependencyInjection 7.x.

amcasey commented 1 month ago

For discussion, please use https://github.com/dotnet/aspnetcore/issues/57231.