Skip to content

Commit

Permalink
ActivatorUtilities.CreateFactory created breaking change from version…
Browse files Browse the repository at this point in the history
… 4.2.2 to 5.0.1 khellang#235
  • Loading branch information
Napoleon Maraidonis committed Nov 20, 2024
1 parent e6a329e commit a25152b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 6 deletions.
5 changes: 2 additions & 3 deletions src/Scrutor/DecorationStrategy.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace Scrutor;

Expand Down Expand Up @@ -30,11 +30,10 @@ internal static DecorationStrategy WithFactory(Type serviceType, string? service

protected static Func<IServiceProvider, object?, object> TypeDecorator(Type serviceType, string serviceKey, Type decoratorType)
{
var factory = ActivatorUtilities.CreateFactory(decoratorType, new[] { serviceType });
return (serviceProvider, _) =>
{
var instanceToDecorate = serviceProvider.GetRequiredKeyedService(serviceType, serviceKey);
return factory(serviceProvider, new object[] { instanceToDecorate });
return ActivatorUtilities.CreateInstance(serviceProvider, decoratorType, instanceToDecorate);
};
}

Expand Down
33 changes: 30 additions & 3 deletions test/Scrutor.Tests/DecorationTests.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using System.Linq;
using Xunit;

namespace Scrutor.Tests;

Expand Down Expand Up @@ -236,6 +236,23 @@ public void Issue148_Decorate_IsAbleToDecorateConcreateTypes()
Assert.NotNull(inner.Dependency);
}

[Fact]
public void Issue235_Decorate_IsAbleToDecorateClassesThatTheirConstructorDoesNotContainTheDecoratedTypeDirectly()
{
var provider = ConfigureProvider(services =>
{
services.AddScoped<Decorated>()
.AddScoped<IDecoratedService>(x => x.GetRequiredService<Decorated>())
.Decorate<IDecoratedService, Decorator3>();
});

using (var scope = provider.CreateScope())
{
var result = scope.ServiceProvider.GetService<IDecoratedService>();
Assert.NotNull(result);
}
}

#region Individual functions tests

[Fact]
Expand Down Expand Up @@ -470,6 +487,16 @@ public Decorator2(DecoratedService decoratedService)
public DecoratedService Inner { get; }
}

public class Decorator3 : IDecoratedService
{
public Decorator3(Decorated inner)
{
Inner = inner ?? throw new ArgumentNullException(nameof(inner));
}

public Decorated Inner { get; }
}

public interface IService { }

private class SomeRandomService : IService { }
Expand Down

0 comments on commit a25152b

Please sign in to comment.