SPSite.Exists leaks SPSites

The Sharepoint Object Model is a painful, leak-prone API to work with. Roger Lamb’s MSDN blog article is a great reference for deciding when you need to dispose of objects and when doing so will break things, but it’s necessity is pretty powerful evidence of how clunky disposal is implemented in this managed code API.

In dev testing, QA found an issue where SPWeb objects were being leaked left and right. It turned out some disposable objects (like SPLimitedWebPartManager) themselves contained disposable objects you had to account for (LimitedWPM’s Web).

Today, I ran into another case with a very minimal set of code I had changed. A quick look in Reflector revealed that as of SP2, even Microsoft can’t always remember when to dispose of objects. The static method SPSite.Exists instantiates a new SPSite object that needs to be disposed of. However, there is no disposal code in the method. There’s no way to work around this issue other than not calling SPSite.Exists. Luckily, no other code in the object model seems to call SPSite.Exists.