Question:
I use the IOC pattern in my project which facilitates the procedure call of the type Resolver.Resolve<IPedido>().GerarPedido()
, however, I didn't want to leave it "loose" like this, I would like to implement the IDisposable
method to use it like this:
using (var pedido = Resolver.Resolve<IPedido>())
{
pedido.GerarPedido();
}
- Can I implement
IDisposable
in a simple class, in this examplePedido
? Would it be good practice? - Does it have a processing cost?
- What is the best way to implement
IDisposable
in this example?
Answer:
The function of the using{}
block, in your own words, is not to "kill" an object so that it "doesn't get loose".
This is the responsibility of the garbage collector .
The Dispose()
method, which is part of the IDisposable interface, is normally used to free resources allocated by the class that, if not freed, could create memory leaks when the object is collected by the GC.
The function of using
is to allow classes that implement IDisposable to be used in such a way as 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 it is necessary to carry out some procedure after using the object and before it is collected by the GC.
Implementing that interface, by itself, does not guarantee that the Dispose()
method is called, but it indicates to the user/consumer that it must do so.