Closed
Description
Description
When trying to use the keyed service with scoped lifetime, InvalidOperationException
thrown with This service provider doesn't support keyed services
message
Reproduction Steps
var serviceCollection = new ServiceCollection();
serviceCollection.AddKeyedScoped<IIdGenerator, GuidIdGenerator>("guid");
using var services = serviceCollection.BuildServiceProvider();
using var scope = services.CreateScope();
var newId = scope.ServiceProvider.GetRequiredKeyedService<IIdGenerator>("guid")
.NewId();
Console.WriteLine(newId);
file interface IIdGenerator
{
string NewId();
}
file sealed class GuidIdGenerator : IIdGenerator
{
public string NewId() => Guid.NewGuid().ToString("N");
}
Expected behavior
Output a Guid value without exception
Actual behavior
Exception with the stack trace below
System.InvalidOperationException: This service provider doesn't support keyed services.
at Microsoft.Extensions.DependencyInjection.ServiceProviderKeyedServiceExtensions.GetRequiredKeyedService(IServiceProvider provider, Type serviceType, Object serviceKey)
at Microsoft.Extensions.DependencyInjection.ServiceProviderKeyedServiceExtensions.GetRequiredKeyedService[T](IServiceProvider provider, Object serviceKey)
Regression?
No response
Known Workarounds
No response
Configuration
.NET 8 Preview 7, 8.0.100-preview.7.23376.3
Windows 11 x64
Other information
No response