Skip to content
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

TryDecorate not working as expected. #224

Open
lukister opened this issue Feb 14, 2024 · 1 comment
Open

TryDecorate not working as expected. #224

lukister opened this issue Feb 14, 2024 · 1 comment

Comments

@lukister
Copy link

lukister commented Feb 14, 2024

If in DI TryAddScoped do not add service to collection if it's already there, then expected behavior for TryDecorate should be the same. But it not passing this test:

public class TestTest
{
    public interface IExampleInterface { }

    public class ExampleImplementation : IExampleInterface { }

    public class ExampleDecorator(IExampleInterface impelmentation) : IExampleInterface { public IExampleInterface Implementation { get; set; } = impelmentation; }

    [Fact]
    public void TestTryDecorate()
    {
        var serviceCollection = new ServiceCollection();
        serviceCollection.AddScoped<IExampleInterface, ExampleImplementation>();
        serviceCollection.TryDecorate(typeof(IExampleInterface), typeof(ExampleDecorator));
        var initCount = serviceCollection.Count;

        serviceCollection.TryDecorate(typeof(IExampleInterface), typeof(ExampleDecorator));
        serviceCollection.TryDecorate(typeof(IExampleInterface), typeof(ExampleDecorator));

        var obj = serviceCollection.BuildServiceProvider()
            .GetRequiredService<IExampleInterface>();

        obj.Should().BeOfType<ExampleDecorator>();

        var obj2 = obj as ExampleDecorator;

        obj2!.Implementation.Should().BeOfType<ExampleImplementation>();
    }
}
@khellang
Copy link
Owner

TryAdd* and TryDecorate are two different things. It works exactly as expected. TryDecorate will (re)decorate everything every time it's called and return true. If nothing is found, it returns false.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants