C#

Composition in C#: Owning Versus Borrowing Dependencies

Nick Cosentino (Dev Leader)
C#

Holding a reference to a collaborator in C# is not the same as owning its lifetime. The article makes the owner/borrower distinction concrete through IDisposable, using scopes and dependency injection lifetimes, and shows why a consumer should not dispose a dependency it merely borrows.

Key points

  • Holding a reference is not ownership: a constructor-injected dependency can still be referenced by the caller and other consumers.
  • A class that creates and stores a disposable child is responsible for cascading cleanup; the sample's sealed OwnedBuffer does this with an idempotent disposed check.
  • using and await using arrange cleanup only; they do not verify that you are allowed to dispose the instance.
  • A borrower does not need to implement IDisposable to avoid disposing the dependency; ByteWriter only validates CanWrite and writes.
  • Container-created services are disposed at the scope or container boundary, but an instance registered directly is never disposed by the framework.
  • A readonly field only prevents field replacement, not mutation of the object, shared side effects or cleanup responsibility.

Why it matters

Naming the ownership boundary explicitly lets you catch premature disposal of shared dependencies and leaking resources during code review instead of in production.

Real-world use

  • Clarifying who cleans up a service class that internally creates a MemoryStream, HttpClient or file handle.
  • Catching accidental Dispose calls on injected scoped dependencies such as a DbContext or stream during code review.
  • Writing an explicit lifetime contract for plugin or adapter components that borrow a caller-supplied resource.
  • Making sure a shared resource registered as an existing instance has exactly one owner responsible for cleanup.

This summary was generated by the agent from the original post on Nick Cosentino (Dev Leader). The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message