Skip to content

Make GetKeyedServices(KeyedService.AnyKey) return all services #95308

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,30 @@ public void ResolveKeyedServices()
Assert.Equal(new[] { service2, service3, service4 }, services);
}

[Fact]
public void ResolveKeyedServicesAnyKey()
{
var service1 = new Service();
var service2 = new Service();
var service3 = new Service();
var service4 = new Service();
var service5 = new Service();
var service6 = new Service();
var serviceCollection = new ServiceCollection();
serviceCollection.AddKeyedSingleton<IService>("first-service", service1);
serviceCollection.AddKeyedSingleton<IService>("service", service2);
serviceCollection.AddKeyedSingleton<IService>("service", service3);
serviceCollection.AddKeyedSingleton<IService>("service", service4);
serviceCollection.AddKeyedSingleton<IService>(null, service5);
serviceCollection.AddSingleton<IService>(service6);

var provider = CreateServiceProvider(serviceCollection);

var allServices = provider.GetKeyedServices<IService>(KeyedService.AnyKey).ToList();
Assert.Equal(6, allServices.Count);
Assert.Equal(new[] { service1, service2, service3, service4, service5, service6 }, allServices);
}

[Fact]
public void ResolveKeyedGenericServices()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -686,17 +686,27 @@ internal bool IsService(ServiceIdentifier serviceIdentifier)
}

/// <summary>
/// Returns true if both keys are null or equals, or if key1 is KeyedService.AnyKey and key2 is not null
/// Returns true if both keys are null or equals, or if either key is KeyedService.AnyKey.
/// </summary>
private static bool KeysMatch(object? key1, object? key2)
{
if (key1 == null && key2 == null)
return true;
// Use reference equality when comparing to AnyKey or null.
// Use key1's definition of equality when comparing key1 and key2.

if (key1 is null)
{
return key2 is null || key2 == KeyedService.AnyKey;
}

if (key1 != null && key2 != null)
return key1.Equals(KeyedService.AnyKey) || key1.Equals(key2);
if (key2 is null)
{
return key1 == KeyedService.AnyKey;
}

return false;
return
key1 == KeyedService.AnyKey ||
key2 == KeyedService.AnyKey ||
key1.Equals(key2);
}

private struct ServiceDescriptorCacheItem
Expand Down