Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SPSite site = new SPSite(SPContext.Current.Web.Url) vs SPContext.Current.Web.Site

Why do some SharePoint examples use

using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
    ...
}

and not just simply?

SPSite site = SPContext.Current.Web.Site;
...

Update

I think I have narrowed the question down to the following:

It seems that I should not use SPContent.Current directly, unless I am certain, that my code runs inside SharePoint. But when would that not be true?

like image 376
Jan Aagaard Avatar asked Nov 08 '11 14:11

Jan Aagaard


2 Answers

Take a look at the best practices documentation on disposing objects in SharePoint 2010 from Microsoft, however there are opposing views.

There are a few key takeaways for SharePoint projects:

  • Always dispose your SPWeb / SPSite objects --> memory leaks
  • Make use of SPContext.Current... when you are sure your code is running in a SharePoint context
    • Unit Tests mean no Sharepoint context
    • External utilities mean no Sharepoint context
    • Powershell means no SharePoint context (e.g. activating a feature with feature receiver might fail)
  • Do not dispose SPContext.Current... but create your own object (again using)

You might have problems with consistency with your multiple SP.. objects.

In the end SPSite site = SPContext.Current.Web.Site; is fine in some instances, but you do not have control over this site object - that might be the problem. If you go for new SPSite(...) you will always have your SPSite and not something SharePoint created and managed for you.

Personally I almost always go for the using structure so all objects are disposed properly afterwards. Alternatively I use SPContext.Current.Web without disposing.

like image 61
Dennis G Avatar answered Oct 31 '22 20:10

Dennis G


It depends on the context in which your code runs. For instance, you need to create a new SPSite instance if you are running within a RunWithElevatedPrivileges block.

like image 4
Nemanja Trifunovic Avatar answered Oct 31 '22 20:10

Nemanja Trifunovic