Skip to content

DI scope disposal (#7205) part 2: scope-resolved services are externally owned, not disposed again by the object tracker #7382

Closed

Description

@thomhurst

Part 2 of #7205, split from #7328. Its branch issue-7205-di-scope-dispose (head b1a2ba27d2) has commits to reuse.

Scope

When a disposable DI scope is disposed (part 1), the object tracker also disposes the services the scope resolved. So each service is disposed twice, and a root singleton that another source shares is disposed too early. Make the scope the only owner of what it resolves.

  • ObjectTracker.MarkExternallyOwned (internal). DependencyInjectionDataSourceAttribute marks what Create returns as externally owned only when the scope is disposable. Document that contract in Create's XML docs.
  • ObjectGraphDiscoverer: IAsyncInitializer objects reached through the properties of an externally owned service, at any depth, are still initialized but not disposed by the tracker. Values of TUnit-injected data-source properties stay with the tracker.
  • An object counted by another source just before it was marked externally owned is released without being disposed (the race that ExternallyOwnedSingletonTests pins).

Files

src/TUnit.Core/Tracking/ObjectTracker.cs, src/TUnit.Core/Discovery/ObjectGraphDiscoverer.cs, src/TUnit.Core/Attributes/TestData/DependencyInjectionDataSourceSourceAttribute.cs, tests/TUnit.UnitTests/ExternallyOwnedSingletonTests.cs, and the _7205 NonDisposableScopeTests and NestedScopeDependencyTests cases.

Acceptance criteria

Activity

  1. added
    bugSomething isn't working
    P1High: significant user-facing bug, fix soon
    on Nov 2, 2026
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

    P1High: significant user-facing bug, fix soonbugSomething isn't workingin-progressWork is in progress

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions