Sunday 27 September 2015

Trying to use an SPWeb object that has been closed or disposed and is no longer valid


You get above error if the code is trying to access the SPSite or SPweb object which was disposed.

Trying to use an SPWeb object that has been closed or disposed and is no longer valid.

If you have code with SPContext, do not dispose the SPWeb or SPSite objects. You can’t dispose the SPcontext objects

i.e.  we cant dispose the object SPContext.current.Web or SPContext.Current.Site directly

when you say SPWeb spWeb= SPContext.Current.Web we are not creating a new instance of spweb, we are referring to the existing instance of the web object which is already there in SPContext. if you use using (SPWeb spWeb= SPContext.Current.Web), using will dispose the spWeb object after control goes out of its scope. here catch is, you are disposing an object which is not created by you.


using (SPSite mySiteCollection = SPContext.Current.Site)
{
using (SPWeb mySite = mySiteCollection.OpenWeb())
{

}
}
Above code gives you exception

so you can rewrite as

using (SPSite mySiteCollection = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb mySite = mySiteCollection.OpenWeb())
{

}
}
or don’t use using when you use SPContext.

Hope this helps!!!

No comments:

Post a Comment