Skip to content
Merged
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
3 changes: 2 additions & 1 deletion src/Scrutor/DecorationStrategy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
20 changes: 20 additions & 0 deletions test/Scrutor.Tests/DecorationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,26 @@ public void ShouldAddServiceKeyToExistingServiceDescriptor()
Assert.EndsWith("+Decorated", key);
}

[Fact]
public void ShouldNotDecorateKeyedServiceWithNonKeyedDecorator()
{
var services = new ServiceCollection();

services.AddKeyedSingleton<IDecoratedService, OtherDecorated>(KeyedService.AnyKey);
services.AddSingleton<IDecoratedService, Decorated>();

services.Decorate<IDecoratedService, Decorator>();

var descriptors = services.GetDescriptors<IDecoratedService>();

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()
{
Expand Down