Aside

Should we need to dispose SPSite and SPWeb objects always?

1. Do NOT Dispose such as SPContext.Current.Site.RootWeb

Why: as shown below RootWeb implementation, create object only when it is null, else it return the current exist root object,

Image

This is simple SingleTon design pattern implementation.

Limitations of using SpContext:

  • SpContext cannot be use when you are calling objects from client environment while implementing Server object model. 
  • You cannot use SpContext for Console or Windows applications.

 2. Need to Dispose objects in below example,

  • Good Coding Practice #1 
    Automatically Disposing 
    C#
    CreatingSPSiteWithAutomaticDisposeNoLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
        } // SPSite object siteCollection.Dispose() is called automatically.
    }
    
  • Dispose of items created by SharePoint methods that return other SPWeb objects (such as OpenWeb). 
    Aa973248.note(en-us,office.12).gifNote:
    This best practice addresses the issue identified by the SharePoint Dispose Checker Tool as SPDisposeCheckID_120.

     

     

    Good Coding Practice #2
    C#

    void OpenWebNoLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb web = siteCollection.OpenWeb())
            {
            } // SPWeb object web.Dispose() automatically called.
        }  // SPSite object siteCollection.Dispose() automatically called.
    }
    
    

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s