IDisposable question

Stesvis 1,041 Reputation points
2022-09-22T00:29:19.41+00:00

I have a class that implements an interface and also IDisposable:

   public interface IMyObject : IDisposable  
   {  
      void MyMethod();  
   }  


   public class MyObject: IMyObject  
   {  
       public void MyMethod()  
       {  
           //...  
       }  
   }  

Then I inject this interface, let's say in a Controller:

   private IMyObject _myObject;  
     
   public MyController(IMyObject myObject)  
   {  
       _myObject = myObject;  
   }  

Then I want to use that class somewhere in the Controller, but I am undecided about the object being disposed properly.
So far I've always wrapped it inside a using statement like:

   public void MyAction()  
   {  
       using var myObject = new MyObject();  
       myObject.MyMethod();  
   }  

This ensures that it's disposed safely.

I was wondering if using the injected object would be exactly the same, or if it could happen that it's not disposed properly?

   public void MyAction()  
   {  
       _myObject.MyMethod();  
   }  
Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
697 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,156 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. SurferOnWww 1,906 Reputation points
    2022-09-22T01:19:56.55+00:00

    Can the following Microsoft document help?

    Dependency injection in ASP.NET Core
    https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-6.0

    See "Disposal of services" section.