9

While testing my solution I receive an error on Feature activation:

Detected use of SPRequest for previously closed SPWeb object. Please close SPWeb objects when you are done with all objects obtained from them, but not before.

This is the way I'm getting SPWeb:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    using (SPWeb web = properties.Feature.Parent as SPWeb)
    {
        ClassOfMine.doYourStuff(web);
    }
}

What am I doing wrong?

  • 1
    Never dispose a web or site you didn't create. – x0n Jul 14 '16 at 18:48
17

how about;

warning: your feature needs to be scoped as web for it to work obviously ;)

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
  // No need to dispose the web istance, as indicated in the "Do not dispose" guidance
  SPWeb web = (SPWeb) properties.Feature.Parent; // added semicolon            

  ClassOfMine.doYourStuff(web);

}

not using feature:

if not then use the spcontext to get the root web

SPContext.Current.Site.RootWeb

or - for the current web

SPContext.Current.Web

or - for a specific web url

SPContext.Current.Site.OpenWeb("Website_URL"))

to use above in feature you would need to use the properties:

use the properties to get the site to get the rootWeb

SPSite site = properties.Feature.Parent as SPSite;
using (SPWeb web = site.RootWeb)
{

}

or - for the current web

SPWeb web = properties.Feature.Parent as SPWeb;

or - for a specific web url

SPSite site = properties.Feature.Parent as SPSite;
using (SPWeb web = site.OpenWeb("Website_URL"))
{

}
  • SPContext.Current.Site.RootWeb worked for me in a way. Thanks :-) – Maurice Klimek Jan 18 '13 at 15:37
  • +1 for the answer, I only edited a little imprecision. Hope you don't mind (as told you on meta, I prefer to improve a valid answer ^_^). See this link for other info blogs.msdn.com/b/rogerla/archive/2009/11/30/… – SPArchaeologist Jan 18 '13 at 16:06
  • lol no probs ;) – Ali Jafer Jan 18 '13 at 16:33
  • 1
    @variable yes your right ;) , didnt spot that myself! I think for the op the solution was the first part, as for the second part iv modified it to explain it better :) – Ali Jafer Jul 28 '14 at 7:13
  • 1
    don't dispose .RootWeb object manually! – dbardakov Apr 15 '16 at 6:51
0

You're doing right. Just the scope of the feature must be web. The "Parent" attribute is always the object of the feature scope.

You're also disposing the object with using.

The only problem with SPContext is that you can't activate the feature from PowerShell as there is no http context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.