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?
Dennis G is correct. Disposing the SPSite/SPWeb/etc is important but make sure you do not dispose the objects that are provided to you by the API directly. It's subtle but critical otherwise your response will never get generated or cause even thread abort situations. In my experience, if I need quick information on the SPSite or SPWeb property that I am sure available to the user context (either a content manager authorized user or anonymous), then using SPContext.Current.* object is great. Otherwise, use the RunWithElevatedPriveleges method to wrap your code and inside that lambda has the following pattern:
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:
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 thissite
object - that might be the problem. If you go fornew SPSite(...)
you will always have yourSPSite
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 useSPContext.Current.Web
without disposing.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 aRunWithElevatedPrivileges
block.