Skip to content

Different behavior of FromKeyedServices attribute in Minimal APIs handler vs class library #102204

@marcominerva

Description

@marcominerva

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

If we use the FromKeyedServices attribute in a class library and the keyed registration is missing, it falls back to the default dependency injection behavior and gets the last registered implementation (even with no key). However, If we use FromKeyedServices directly in a Minimal API endpoint handler and the key does not exist, it throws an exception.

Expected Behavior

The FromKeyedServices attribute should behave in the same way in every context.

Steps To Reproduce

Minimal repro here: https://github.com/marcominerva/KeyedServicesIssue

Exceptions (if any)

When using FromKeyedServices directly in a Minimal API endpoint handler:

System.InvalidOperationException: No service for type 'KeyedServicesIssue.Library.IDependency' has been registered.
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetRequiredKeyedService(Type serviceType, Object serviceKey, ServiceProviderEngineScope serviceProviderEngineScope)
at lambda_method2(Closure, Object, HttpContext)

When using FromKeyedServices in a class library, no exception at all is thrown, even if the key does not exist.

.NET Version

8.0.204

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions