Gonzalo Lorieto
Gonzalo Lorieto

Reputation: 645

Circular Dependency Injection in constructors

Given this scenario:

public class A : IA
{
    private IB _ib { get; }
    public A(IB ib)
    {
        _ib = ib;
    }
}

public class B : IB
{
    private IA _ia { get; }
    public B(IA ia)
    {
        _ia = ia;
    }
}

And at Startup.cs both are registered as Singleton.

Why does this doesn't fall into circular dependency?

Upvotes: 1

Views: 200

Answers (1)

Scott Hannen
Scott Hannen

Reputation: 29302

If, as indicated in your comments, the dependencies are registered like this:

services.AddSingleton<IA, A>();
services.AddSingleton<IB, B>();

...resolving either IA or IB will fail with an exception. This is provable with a unit test.

[TestMethod]
public void TestCircularDependency()
{
    var services = new ServiceCollection();
    services.AddSingleton<IA, A>();
    services.AddSingleton<IB, B>();
    var provider = services.BuildServiceProvider();
    var a = provider.GetService<IA>();
    var b = provider.GetService<IB>();
}

Either resolution fails with an exception:

System.InvalidOperationException: A circular dependency was detected for the service of type 'UnitTestProject1.IB'.

For this not to fail is impossible. Things frequently happen in our code that appear to be impossible, but in virtually every case the cause is an assumption that can't be correct.

You've also mentioned that it works in one environment but not in another. The assumption (which I've made lots of times) is that the same code is running in both environments, but in this case it's not.

The only way that IA can be resolved in this case is if there is another implementation of IA or another implementation of IB (or very unlikely - null is injected as the dependency into one or the other.)


This sort of problem is interesting because when we see something that appears to be impossible, our tendency (mine at least) is often to stare at it wondering how the impossible is happening. Once we've determined that what we think is happening is impossible, that's an indication that we should begin questioning every other assumption which has led us to that conclusion. One of them must be false.

Upvotes: 2

Related Questions