When developing a feature receiver, you typically need a reference to one of the Object Model classes which represent the feature scope, that being;
- Web – SPWeb
- Site – SPSite
- WebApplication – SPWebApplication
- 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 }
2 thoughts on “SharePoint: SPFeatureReceiverProperties.Feature.Parent Reference”