When is it advisable for a class to implement IDisposable?

8

I use the IOC standard in my project which facilitates the procedure call of type Resolver.Resolve<IPedido>().GerarPedido() , but I did not want to leave it "loose" in this way, I would like to implement the method IDisposable use like this:

using (var pedido = Resolver.Resolve<IPedido>())
{
  pedido.GerarPedido();
}
  • Can I implement IDisposable in a simple class, in this example, Pedido ? Would it be a good practice?
  • Is processing cost?
  • How best to implement IDisposable in this example?
  • asked by anonymous 15.11.2015 / 18:27

    2 answers

    4

    The function of block using{} , using your words, is not to "kill" an object so that it "does not get loose". This is the responsibility of the garbage collector .

    The Dispose() method, which is part of the IDisposable interface, is usually used to free resources allocated by the class that, if not released, could create memory leaks when the object was collected by GC.

    The function of using is to allow classes that implement IDisposable to be used in order to guarantee the execution of the Dispose() method at the end of its use, even if an exception is thrown.

    Thus, the implementation of the IDisposable interface is only recommended when some procedure is required after using the object and before it is collected by the GC.

    Implementing this interface by itself does not guarantee that the Dispose() method is called, but tells the user / consumer what to do.

        
    15.11.2015 / 19:14
    6
  • You can implement, of course. You can do whatever you want.

  • There is processing cost. Whether it will be a problem or not.

  • The best way is not to implement. After all, it does not seem to use some external resource that the application has no control, so it does not make sense to implement it.

  • Unless you have something obscure within this request, you have no reason to implement this interface and adopt the layout pattern. And if you have any reason, this class is probably implemented in the wrong way. I can not give details because the question does not give details about the class.

    The object must be claimed by the garbage collector at the right time and will not be released. If it is not happening this is because it has problems. GC is smart, he knows when to do it. He just is not miraculous. If something is preventing him from collecting, he has to solve this problem.

    Read more about the subject .

    About .Net memory management .

        
    15.11.2015 / 18:39