I want to access SPWeb object in feature under its FeatureActivated method. There are two ways to do this:

Public Override void FeatureActivated(SPFeatureReceiverProperties properties) {

//Method 1 

 SPWeb web = properties.Feature.Parent as SPWeb;

//Method 2

SPSite site = new SPSite("http://merdev-moss:5050");
SPWeb web = site.OpenWeb();


Whats the differencce between two methods ? Which one is best under which scenario ?

3 Answers 3


You don't need to put SPWeb oWebsiteRoot = SPContext.Current.Site.RootWeb in the using statement, because it's obtained from SPContext.Current.Site and will be automatically disposed.

  • yup your right, i only quickly copied it from msdn ;), but yes the spcontext handles it for us :P
    – Ali Jafer
    Dec 6, 2012 at 17:00
  • But what you Think, if i put; SPSite site = properties.Feature.Parent as SPSite. Its scope will be SPSite ? I don't need to change the method if i change the scope now. is it right ?
    – SPBeginer
    Dec 7, 2012 at 10:49


properties.Feature.Parent will give you SPWeb in the context the FeatureActivated Event is being called... That means you should not dispose this object, since it is the current context which is activating the feature!

However, if you use:
SPSite site = new SPSite("http://merdev-moss:5050"); SPWeb web = site.OpenWeb();

this means you are creating a New Context and you need to dispose this connection which will be automatically done if you use it inside using

using (SPSite site = new SPSite("http://merdev-moss:5050"))
    using (SPWeb web = site.OpenWeb())
       //do stuff

The first option means that the feature needs to be scooped as web to use that method and if you change the scope you need to change the method as it will throw an exception. Use that method only if you need the feature as web and nothing else! same goes for any scope that you choose.

The second I prefer as it is not dependant on the scope of the feature,

for me I would use this:

SPWeb oWebsiteRoot = SPContext.Current.Site.RootWeb

more detail on what you can use to achive what you want can be found here:


The first one is using the current web, the second is creating a new instance that you need to dispose of ;)

hope it helps :)

  • If you activate your feature from Powershell, your feature activation will fail, because there you don't have an SPContext. That's why it's always better to use the properties.Feature.Parent property.
    – Norbert
    Dec 6, 2012 at 17:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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