I have an object that is expensive to create, which uses some unmanaged resources that must be explicitly freed when done with and so implement IDisposable(). I would like a cache for instance of these expensive resources so that the creation cost is minimized, but I am having trouble knowing how to deal with the disposal.
If the methods that use the objects are responsible for the disposal then I end up with disposed instances in the cache, which then have to be recreated, defeating the point of the cache. If I don't dispose the objects in the methods that use them then they never get disposed. I thought I could dispose them when they are taken out of the cache, but then I might end up disposing an instance which is still being used by a method.
Is it valid to just let them go out of scope and be collected by the garbage collector and free up the resources at that point? This feels wrong and against the idea of them being disposable...