SharePoint: SPFeatureReceiverProperties.Feature.Parent Reference

When developing a feature receiver, you typically need a reference to one of the Object Model classes which represent the feature scope, that being;

  1. Web – SPWeb
  2. Site – SPSite
  3. WebApplication – SPWebApplication
  4. Farm – SPFarm

Since within a feature receiver you don’t know how it’s being activated/installed (either using the UI or the command-line) you shouldn’t use SPContext to get this information. Instead you can use the SPFeatureReceiverProperties.Feature.Parent reference which is passed to the feature receiever code.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
	var web = properties.Feature.Parent as SPWeb;
	var site = properties.Feature.Parent as SPSite;
	var webApp = properties.Feature.Parent as SPWebApplication;

As shown, it’s straight forward enough to get a reference to the required object type where the feature is being activated.

For Farm scoped features though, it’s a little different.  

The SPFeatureReceiverProperties.Feature.Parent reference doesn’t refer to an SPFarm, but is a reference to the SPWebService class.

Through this class you can access all aspects of the farm environment, including of course the Farms Web Applications, Servers etc.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
	var svc = properties.Feature.Parent as SPWebService;
	foreach (var webApp in svc.WebApplications)
		// do stuff with the web applications of the farm

Published by

Phil Harding

SharePoint Consultant, Developer, Father, Husband and Climber.

2 thoughts on “SharePoint: SPFeatureReceiverProperties.Feature.Parent Reference

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.