How to ensure that the instantiation of a class is done only through the "using"?

2

I am creating a DLL with some database functionality (ADO.Net). It would be very convenient to ensure that the instantiation of connections is always only via using (block), so do not forget to call Dispose() / Close() . But you can also forget to use using .

How to ensure that using is used in all classes with IDisposable implementation?

    
asked by anonymous 12.03.2015 / 21:22

2 answers

2

Only within using , no.

The idea is that the .NET Garbage Collector is able to detect when an object will no longer be used within the context of the application, expiring and deleting the object alone. Of course using Dispose is much more elegant, but that can not be required.

    
12.03.2015 / 21:32
3

It is recommended that you do this anytime a class implements the IDisposable ". Unfortunately the compiler and Visual Studio do not guarantee this. I even understand that the compiler does not enforce because there are rare legitimate cases that you should not use this form.

But an additional configurable tool should help. Fortunately there is the Resharper that can alert you that whenever the class you are instantiating is not in a using . It's the only way I know it, but other competing plugins should have something similar. Obviously the alert is only made for classes that implement IDisposable .

You can also customize the new .Net Compiler Platform to do this. I do not have data to tell how to do this and it should not be too trivial, though it may not be too complex either. The idea of the new compiler platform is just to let people extend their operation as needed.

    
12.03.2015 / 21:40