simpleinjector / SimpleInjector

An easy, flexible, and fast Dependency Injection library that promotes best practice to steer developers towards the pit of success.
https://simpleinjector.org
MIT License
1.21k stars 154 forks source link

Different Flowing Scopes Returning Same Instance of a Scoped Object from within a Singleton constructor #966

Closed pnicoletti88 closed 9 months ago

pnicoletti88 commented 1 year ago

I have two different Flowing Scopes, but they are returning the same instance of a scoped dependency.

To Reproduce

var container = new Container();
container.Options.DefaultScopedLifestyle = ScopedLifestyle.Flowing;
container.Register<Singleton>(Lifestyle.Singleton);
container.Register<Scoped>(Lifestyle.Scoped);

container.GetInstance<Singleton>();

public class Scoped { }

public class Singleton
{
    public Singleton(Container c)
    {
        var scope1 = new Scope(c);
        var scope2 = new Scope(c);

        if (object.ReferenceEquals(scope1.GetInstance<Scoped>(), scope2.GetInstance<Scoped>()))
        {
            Assert.Fail("Resolved the same instance.");
        }
    } 
}

In this example the Assert.Fail is being hit. I do not believe this is expected.

Additional context

dotnetjunkie commented 1 year ago

Thanks for this repro. Using the supplied code I can confirm that this is a bug. I haven't fully investigated what the cause of the bug is, but what I see is that the problem only appear in a very specific situation, which is when instances are being resolved from within the constructor of a singleton component.

I don't have a solution yet, but a workaround is to either:

  1. Make the component anything but singleton
  2. Move the calls to GetInstance out of the constructor.
  3. Set EnableAutoVerification to false.

Will try to fix this in the following patch or minor release.

dotnetjunkie commented 9 months ago

Sorry for the delay of almost a year, but this bug finally got fixed in v5.4.4.