Roger Lamb's SharePoint Developer Blog

SharePoint 2007 UserProfiles.PersonalSite Property Leak

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!

Published Wednesday, January 14, 2009 6:31 PM by Roger Lamb

Comments

 

Confluence: SharePoint Development Wiki said:

SPSite and SPWeb implement the IDisposable interface

January 15, 2009 3:08 AM
 

Roger Lamb's SharePoint Developer Blog said:

Last Updated: January 28, 2009 Overview Windows SharePoint Services (WSS 3.0) and Microsoft Office SharePoint

January 28, 2009 11:45 PM
Anonymous comments are disabled

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker