khellang / Scrutor

Assembly scanning and decoration extensions for Microsoft.Extensions.DependencyInjection
MIT License
3.67k stars 239 forks source link

Upgrade from 4.2.2 to 5.0.1 breaks decoration #237

Open lukasvavrek opened 1 month ago

lukasvavrek commented 1 month ago

Hi, while playing around updating and upgrading my app I run into a compatibility issue.

Here is an example of the registration code:

public static class DependencyInjection
{
    public static IServiceCollection AddApplication(this IServiceCollection services)
    {
        services.Scan(scan =>
            scan.FromCallingAssembly()
                .AddClasses(classes => classes
                    .AssignableTo(typeof(IRequestHandler<,>))
                    .NotInNamespaceOf<IRequestHandlerBehavior>())
                .AsImplementedInterfaces()
                .WithTransientLifetime()
        );

        services.Decorate(typeof(IRequestHandler<,>), typeof(RequestExceptionHandler<,>));

        return services;
    }
}

While this works as expected in version 4.2.2, in 5.0.1 I am running into:

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.Populate()
   at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)
   at Microsoft.Extensions.Hosting.HostApplicationBuilder.Build()
   at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()
   at Program.<Main>$(String[] args) in /XXX/Program.cs:line 15

Let me please know if I can provide some useful information!

khellang commented 1 month ago

Thanks for the bug report! Looks like it comes from deep within the container code. Need to dig a bit here 😅

Mike-E-angelo commented 3 weeks ago

Related: #235

ajdean commented 2 days ago

From what I have found if you are targeting net8.0 then decoration works fine.

If you are targeting something below that (e.g. net6.0 or net7.0), then you will need to ensure you have added Microsoft.Extensions.DependencyInjection version >= 8.0.0 otherwise I think it fails due to keyed services not being supported.