문제

I'm hoping someone can help me out. I need to get the root web of the current site from the SPContext. It's easily done with the following

SPContext.Current.Site.RootWeb

I'm comfortable with the idea that the SPSite object here at SPContext.Current.Site.RootWeb shouldn't be disposed of, but what about the SPWeb object I'm getting from the SPSite. Will, when the SPSite get's disposed, the rootweb SPWeb get disposed to? Or do I need to dispose of it myself?

도움이 되었습니까?

해결책

Calls to SPSite.RootWeb should not be disposed. Disposing the SPSite will also dispose the RootWeb.

There is a bug in SPDisposeCheck where it flags if you do dispose it, and if you don't (damned either way!) I detailed how I solved this in this blog post, as you can't use an SPDisposeCheckIgnore attribute in elevated privileges blocks.

다른 팁

No you should not. You should only dispose objects you are in control of. Because the context is something created by SharePoint you do not dispose of this as other objects may be dependent upon this.

If you were to create your own instance of an SPWeb from this objects properties than it would need to be disposed. I.e..

using (SPSite site = new SPSite(SPContext.Current.Site.RootWeb.Url))
using (SPWeb web = site.OpenWeb()) {
 // do something
}

Here is an article on the best practices of disposing SharePoint objects.

http://msdn.microsoft.com/en-us/library/aa973248(v=office.12).aspx

You should normally use SPSite and SPWeb in a using clause.

using (SPSite site = new SPSite("http://mysite.sharepoint.com"))
{
    using (SPWeb web = site.OpenWeb())
    {
        // TODO: code for using SPWeb object
    }
}

This automatically will correctly release the SPWeb object after you are done with it.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top