0

What is the difference between below way of getting the reference of SPSite object in FeatureActivated() of sharepoint?

1.

 public override void FeatureActivated(SPFeatureReceiverProperties
    properties)
        {
           SPSite site = properties.Feature.Parent as SPSite;
        //some code
        }

                 **VS**

2.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
   SPSite site = SPContext.Current.Site;
//some code
}

1 Answer 1

4

You can't get SPContext inside handlers - this is by design. You should use event properties passed as argument to the handler to get reference to current web, list item etc.

Timer Jobs, Feature Receivers, Service Application Solutions are not invoked synchronously by user action, so they are not associated with HTTPRequest and thus they do not have access to SPContext.

You have to get it :

SPSite site = properties.Feature.Parent as SPSite;

http://social.technet.microsoft.com/forums/sharepoint/en-US/6eed2ed3-85de-4a20-936b-79f87cf42385/why-we-dont-get-spcontext-in-event-receiver

2
  • 2
    You can use SPContext, but it will only work when the feature is being activated via the GUI. It will fail with a null pointer if the feature activates through PowerShell. Hence, always get the site or web object from the properties Sep 6, 2014 at 16:21
  • @RobertLindgren Correct. I tried to activate feature through powershell and got null ponter exception.
    – nbi
    Sep 7, 2014 at 10:22

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.