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 ca
To (mis-)quote Raymond Chen: Every cache without an expiration policy is a leak
So, set a clear cache expiration policy, and let the cache dispose them as the normal case. This still leaves application shutdown to be handled.
If your unmanaged ressources are owned by the process, you can let the process release them on shutdown.
If the unmanaged ressources are not owned by the process, you need to detect shutdown and explicitely Dispose the cached elements.
If you can't detect process shutdown reliably, and the managed ressources are expensive, the unmanaged ones are not, separate the managed from the unmanaged ressources, and let the cache keep only the managed ones.
When the unmanaged ressources are expensive so they need caching, and they are not owned by the process, and you cannot detect process shutdown reliably and you cannot afford to leak them, then your problem cannot be solved.