diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection.Specification.Tests/src/ServiceProviderIsKeyedServiceSpecificationTests.cs b/src/libraries/Microsoft.Extensions.DependencyInjection.Specification.Tests/src/ServiceProviderIsKeyedServiceSpecificationTests.cs index 7321fe0e1874cf..25c3532e48d083 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection.Specification.Tests/src/ServiceProviderIsKeyedServiceSpecificationTests.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection.Specification.Tests/src/ServiceProviderIsKeyedServiceSpecificationTests.cs @@ -125,5 +125,30 @@ public void NonKeyedServiceWithIsKeyedService() Assert.NotNull(serviceProviderIsService); Assert.True(serviceProviderIsService.IsKeyedService(typeof(IFakeService), null)); } + + [Theory] + [InlineData(typeof(IServiceProvider))] + [InlineData(typeof(IServiceScopeFactory))] + [InlineData(typeof(IServiceProviderIsService))] + [InlineData(typeof(IServiceProviderIsKeyedService))] + public void BuiltInServicesWithIsKeyedServiceOnlyReturnTrueForNullServiceKey(Type builtInServiceType) + { + if (!SupportsIServiceProviderIsKeyedService) + { + return; + } + + // Arrange + var provider = CreateServiceProvider(new TestServiceCollection()); + + // Act + var serviceProviderIsService = provider.GetService(); + + // Assert + Assert.NotNull(serviceProviderIsService); + Assert.True(serviceProviderIsService.IsKeyedService(builtInServiceType, null)); + Assert.False(serviceProviderIsService.IsKeyedService(builtInServiceType, new object())); + Assert.False(serviceProviderIsService.IsKeyedService(builtInServiceType, KeyedService.AnyKey)); + } } } diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs index 490337d14b028c..3c3d3c3e897cc4 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs @@ -814,10 +814,11 @@ internal bool IsService(ServiceIdentifier serviceIdentifier) // These are the built in service types that aren't part of the list of service descriptors // If you update these make sure to also update the code in ServiceProvider.ctor - return serviceType == typeof(IServiceProvider) || - serviceType == typeof(IServiceScopeFactory) || - serviceType == typeof(IServiceProviderIsService) || - serviceType == typeof(IServiceProviderIsKeyedService); + return serviceIdentifier.ServiceKey is null && + (serviceType == typeof(IServiceProvider) || + serviceType == typeof(IServiceScopeFactory) || + serviceType == typeof(IServiceProviderIsService) || + serviceType == typeof(IServiceProviderIsKeyedService)); } private struct ServiceDescriptorCacheItem