Resource Cleanup functional way

For some applications there might be times when expensive resources must be cleaned up properly or there might be times where your clients are being irresponsible and forget to wrap your class in using statements resulting in memory leaks or open database connections.  These might be a good time to implement the following strategy by where you take full control/responsibility of cleaning your own resources and not allow anybody else to instantiate a new instance of your class.  Lets say we have the following class and a repository implementation mimicking a database service:

person

repo

The first thing you’ll notice in the repository class is that it has a “private constructor” to disallow any callers to create a new instance of this class.  Then it provides to static “Use” methods for the clients, one is void and the other returns T.  Within the Use methods is where you would take control of cleaning up whatever resources needs to be cleaned up, freeing the clients of your class from that burden.  I also believe that cleaning up after yourself is an internal concern and an implementation detail that other classes shouldn’t know about nor care about!  Now the clients can use your class as follows:

main

If you run the program you’ll see that the Dispose method is called each time as you’d expect and the client does not need to remember to wrap any statements in using/try-finally block.

References: Venkat Subramaniam