Skip to content

ServiceProvider.GetRequiredService hangs #132359

Description

@znakeeye

Description

Targeting .NET 10, using Microsoft.Extensions.DependencyInjection version 10.0.11.

Building the service provider with validateScopes = true I would expect it to find the cyclic dependency in the code below. If anything, it should throw when resolving the Foo service. Instead, when resolving Foo, it hangs. It looks like a bug, but maybe it's a known limitation?

Sample code

using Microsoft.Extensions.DependencyInjection;

namespace ServiceCollectionTest;

public class OptionalServiceFactory(Foo foo)
{
    public Dependency CreateDependency() => new();
}

public class Dependency
{
}

public class Foo(Dependency dependency)
{
}

internal class Program
{
    static void Main(string[] args)
    {
        var services = new ServiceCollection();

        services.AddScoped<Foo>();
        services.AddScoped<OptionalServiceFactory>();
        services.AddScoped(sp => sp.GetRequiredService<OptionalServiceFactory>().CreateDependencyA());

        var sp = services.BuildServiceProvider(validateScopes: true);

        var scope = sp.CreateScope();
        var foo = scope.ServiceProvider.GetRequiredService<Foo>(); // Hangs!
        
        Console.WriteLine("OK");
    }
}

Reproduction Steps

See sample code.

Expected behavior

GetRequiredService() should throw an exception (or better, scope validation should detect the cyclic dependency).

Actual behavior

GetRequiredService() hangs indefinitely.

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions