I am trying to add a propertie to a WebAplication on FeatureInstalled event receiver.

public override void FeatureInstalled(SPFeatureReceiverProperties properties)
            SPContext.Current.Site.WebApplication.Properties["test"] = @"test";

When I deploy my applciation from VS2010 I get:

Error occurred in deployment step 'Add Solution': Object reference not set to an instance of an object.

This error has only occured since adding this event reciever. What am I doing wrong?


FeatureInstalled - handles the event that is raised after a Feature is installed, which means it gets executed when the WSP is loaded into the Farm. So, at that time no SPContext, SPWeb or SPSite exists

  • Do you know what I can grab hold of? – John Feb 3 '12 at 16:32
  • Why can't you use it within the FeatureActivated? msdn.microsoft.com/en-us/library/… – Falak Mahmood Feb 3 '12 at 16:34
  • Coudl I use something like var web = properties.Feature.Parent as SPWebApplication; – John Feb 3 '12 at 16:36
  • yes, provided your Feature is of scope Web application... – Falak Mahmood Feb 3 '12 at 16:48

You could use var web = properties.Feature.Parent as SPWebApplication; like you stated above.

The reason that you shouldn't use SPContext in an event receiver event is that you may not always be running in a web application context, inside the IIS w3wp.exe process.

Take a FeatureActivated event for instance. If you activate the feature from the UI, a web page, your call to SPContext would work because you're running in the w3wp process and have an HttpContext to call upon. If you activate that same feature from powershell, you're running in a powershell process, no access to HttpContext, calls to SPContext.Current will fail. Same goes for deploying from Visual Studio (devenv.exe process), and code inside timer jobs (owstimer.exe).

Hope that helps.

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.