0

I wanted to know if when you inject your DbContext with DI in a class, within the methods calling that context, should you use the using scope as well ? Or does DI knows about disposal after the method has been executed and/or does transient by default and it's safe ?

  • Related: https://stackoverflow.com/questions/30283564/dependency-injection-and-idisposable/30287923#30287923 – Steven Jun 04 '23 at 09:50

2 Answers2

1

The default registration of a DbContext class in ID is as Scoped Service.

The Dependency Injection library will handle disposal. This is described in documentation here.

Ibrahim Hamaty
  • 540
  • 2
  • 18
1
  1. When you inject a DbContext using dependency injection (DI), you generally don't need to use the using scope explicitly within the methods calling that context.
  2. In the case of a transient registration for your DbContext, a new instance of the context will be created for each method call, and the DI container will automatically dispose of it once the method execution is complete. Therefore, you don't need to manually dispose of the context using the using statement.

Microsoft Docs

Dhiren Patel
  • 630
  • 8
  • 16