The following edge case applies to MOSS 2007 (and not WSS 3.0). When using the following pattern the property Microsoft.Office.Server.UserProfiles.PersonalSite requires a Dispose() call before leaving scope if you use the property in your code. Below is an example of a common usage of PersonalSite property.
void PersonalSiteLeak()
{
// open a site collection
using (SPSite siteCollection = new SPSite("http://moss"))
{
UserProfileManager profileManager = new UserProfileManager(ServerContext.GetContext(siteCollection));
UserProfile profile = profileManager.GetUserProfile("domain\\username");
SPSite personalSite = profile.PersonalSite; // will leak
}
}
void PersonalSiteNoLeak()
{
// open a site collection
using (SPSite siteCollection = new SPSite("http://moss"))
{
UserProfileManager profileManager = new UserProfileManager(ServerContext.GetContext(siteCollection));
UserProfile profile = profileManager.GetUserProfile("domain\\username");
using (SPSite personalSite = profile.PersonalSite)
{
// ...
}
}
}
From a web context performance perspective it is more efficient to get your UserProfile object in the following example:
UserProfile myProfile = ProfileLoader.GetProfileLoader().GetUserProfile();
using (SPSite personalSite = myProfile.PersonalSite)
{
// ...
}
Note the use of ProfileLoader to get the shared UserProfile instance for my own profile. There is no need to open a fresh SPSite in the case where you’re browsing a page. Additionally, if your web part is designed to be placed on a My Site, there is even a shared PersonalSite instance that will be disposed for you and does not require you to call Dispose() with this technique:
IPersonalPage currentMySitePage = this.Page as IPersonalPage;
if (currentMySitePage != null && !currentMySitePage.IsProfileError)
{
SPSite personalSite = currentMySitePage.PersonalSite; // will not leak
// ...
}
Thanks to Microsoft’s Anant Dimiri and Bryant Fong for their contributions!