Skip to content

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

Closed

Description

@pnicoletti88

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

  • Adding container.Options.EnableAutoVerification = false; fixes the problem.
  • Running against latest version, 5.4.1

Activity

  1. changed the title [-]Different Flowing Scopes Returning Same Instance of a Scoped Object[/-] [+]Different Flowing Scopes Returning Same Instance of a Scoped Object from within a Singleton constructor[/+] on Jan 11, 2023
  2. dotnetjunkie commented on Jan 11, 2023

    @dotnetjunkie
    Collaborator

    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.

  3. added this to the v5.5 milestone on Jan 2, 2024
  4. added 2 commits that reference this issue on Jan 5, 2024
    922dc8b
    bec51f8
  5. dotnetjunkie commented on Jan 5, 2024

    @dotnetjunkie
    Collaborator

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

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

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions