Skip to content

TryDecorate not working as expected. #224

Description

@lukister

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>();
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions