diff --git a/src/Scrutor/DecorationStrategy.cs b/src/Scrutor/DecorationStrategy.cs index 877ad4b2..a87832c3 100644 --- a/src/Scrutor/DecorationStrategy.cs +++ b/src/Scrutor/DecorationStrategy.cs @@ -16,7 +16,8 @@ protected DecorationStrategy(Type serviceType, string? serviceKey) public string? ServiceKey { get; } public virtual bool CanDecorate(ServiceDescriptor descriptor) => - string.Equals(ServiceKey, descriptor.ServiceKey as string, StringComparison.Ordinal) && CanDecorate(descriptor.ServiceType); + // object.Equals is used to support decorating services with object keys (e.g., KeyedService.AnyKey). + Equals(ServiceKey, descriptor.ServiceKey) && CanDecorate(descriptor.ServiceType); protected abstract bool CanDecorate(Type serviceType); diff --git a/test/Scrutor.Tests/DecorationTests.cs b/test/Scrutor.Tests/DecorationTests.cs index 0081257f..dbbeaf0c 100644 --- a/test/Scrutor.Tests/DecorationTests.cs +++ b/test/Scrutor.Tests/DecorationTests.cs @@ -84,6 +84,26 @@ public void ShouldAddServiceKeyToExistingServiceDescriptor() Assert.EndsWith("+Decorated", key); } + [Fact] + public void ShouldNotDecorateKeyedServiceWithNonKeyedDecorator() + { + var services = new ServiceCollection(); + + services.AddKeyedSingleton(KeyedService.AnyKey); + services.AddSingleton(); + + services.Decorate(); + + var descriptors = services.GetDescriptors(); + + Assert.Equal(3, descriptors.Length); + + var nondecorated = descriptors.SingleOrDefault(x => x.IsKeyedService && x.KeyedImplementationType == typeof(OtherDecorated)); + + Assert.NotNull(nondecorated); + Assert.Equal(KeyedService.AnyKey, nondecorated.ServiceKey); + } + [Fact] public void CanDecorateExistingInstance() {