views:

66

answers:

2

Hi all

What is the best way to obtain the current site/web/list ?

Option 1 - Reusing existing objects

        SPSite site = SPContext.Current.Site;
        SPweb web = SPContext.Current.Web;
        SPList list = SPContext.Current.List;

Option 2 - Creating new objects

        SPSite site = new SPSite(SPContext.Current.Site.ID); // dispose me
        SPweb web = site.OpenWeb(SPContext.Current.Web.ID); // dispose me
        SPList list = web.Lists[SPContext.Current.List.ID];

I experienced problems when using option 1 in some situations. Since then I chose the 2nd option and it worked fine so far.

What is your opinion on this? I is generally better to go with option 2? Other suggestions?

+3  A: 

I normally go with option 2 (which I believe si the approach recommended by Microsoft), but I tend to wrap things using using to ensure they are disposed of properly. Example:

using (SPSite site = new SPSite("MY SITE URL"))
{
  using (SPWeb web= site.OpenWeb())
   {
       // Do stuff
   }
} 

This approach allows you to be explicit about when objects are created and destroyed.

Cocowalla
That's also the way to go when using RunWithElevatedPrivileges() to get the objects in the correct security context.
Flo
+3  A: 

Do use Option one, because it's more resource-efficient as you don't need to create new object (For example OpenWeb method involves querying database to do it's job). But you are not allowed to dispose objects from SPContext, that will definitely cause you problems.

You must use Option Two if your code is not run in context of application pages (like SharePoint timer or Workflow), because SPContext.Current object will be null.

Link

And yes, if you open SPWeb or SPSite object, you MUST dispose it.

Janis Veinbergs
Option 1 _is_ going to be more efficient, but there will be times when you can't use it (when you want a site not in the current context, for example). I'd prefer to use option 2 in all situations, as it provides a consistent way of doing things.
Cocowalla
Are you kidding? You'd rather make a database round trip even if it's unnecessary?
OedipusPrime
Of course it depends on the application in question, but quite possible, yes. Performance is not the only consideration - there is also readability, maintainability and safety (e.g. making sure you properly dispose of SharePoint objects). Do you only program in assembly, or do you add unnecessary overheads using a high-level language? ;)
Cocowalla