Question

I'm just looking for a bit of sanity check on this one!

I'm looking at many classes that have SPSite or SPWeb as a constructor for the class.

The class is instantiated using SPContext.Site as the SPSite parameter

e.g.

public MyClass {
  SPWeb _web;
  public MyClass(SPSite site) {
    _web = site.RootWeb;
  }
  // Other methods that make use of _web
}

Should _web be disposed of? Is _web just a pointer to SPContext.Site.RootWeb or is there another copy of SPWeb that need to be disposed of?

I know that with SPContext.Site.OpenWeb() you should call Dispose().

So what about with the above usage?

Will passing SPSite / SPWeb as assigning it to a local variable always just have the reference to the same SPContext ?

Was it helpful?

Solution

In your case _web doesn't need to be disposed as you are getting it from the RootWeb and web objects retrieved from RootWeb need not to be disposed.

EIDT

Also, if the SPSite object passed as parameter to the constructor is derived from the SPContext, it doesn't need to be disposed. Otherwise it needs to be disposed either in the called class or from the calling class depending on the requirement.

OTHER TIPS

Do not explicitly call Dispose() on the SPSite.RootWeb property. The dispose cleanup will be handled automatically by the SharePoint and the .NET framework. For existing SharePoint customizations removal of explicit RootWeb Dispose is recommended to avoid an edge case condition where the SPContext.Current.Web has equality to the SPSite.RootWeb. Problems can occur when disposing RootWeb when obtained from any variation of SPContext (For Example: SPContext.Site.RootWeb, SPContext.Current.Site.RootWeb and GetContextSite(Context).RootWeb ).

For more visit...MSDN

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top