Share via

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();  
   }  
Developer technologies | .NET | Entity Framework Core
Developer technologies | ASP.NET Core | Other
0 comments No comments

1 answer

Sort by: Most helpful
  1. SurferOnWww 6,016 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.

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.