Skip to content

Dependency Injection Scope shared between tests #2930

@viceroypenguin

Description

@viceroypenguin

Review the following minimal repro:

using Microsoft.Extensions.DependencyInjection;

public sealed class Dependency
{
    private static int _value = 0;
    public int Value { get; } = Interlocked.Increment(ref _value);
}

public sealed class DependencyInjectionClassConstructor : DependencyInjectionDataSourceAttribute<IServiceScope>
{
    private readonly IServiceProvider _serviceProvider = BuildServiceProvider();

    private static IServiceProvider BuildServiceProvider()
    {
        var services = new ServiceCollection();
        services.AddScoped<Dependency>();
        return services.BuildServiceProvider();
    }

    public override object? Create(IServiceScope scope, Type type) =>
        ActivatorUtilities.GetServiceOrCreateInstance(scope.ServiceProvider, type);

    public override IServiceScope CreateScope(DataGeneratorMetadata dataGeneratorMetadata) =>
        _serviceProvider.CreateAsyncScope();
}

[DependencyInjectionClassConstructor]
public sealed class ActualTestClass(Dependency dependency)
{
    [Test]
    [Arguments(1)]
    [Arguments(2)]
    public void Test1(int testNumber)
    {
        Console.WriteLine(dependency.Value);
    }
}

Actual:

When running this, the output is:

1
1

indicating that the same instance of Dependency was provided twice to Test1.

Expected:

When running this, the output should be:

1
2

or

2
1

indicating that separate scopes were created for each Test1() test.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions