Question

We have a number of web-scoped features all stapled to a site definition, so they are all activated in turn when a web is created from the definition.

It seems the feature receivers all share the same reference to the created web, accessed via (SPWeb)properties.Feature.Parent in the FeatureActivated method. This is normally OK - one feature receiver makes some changes to the web, updates it, and passes the updated web to the next receiver, and so on.

However, one of our features applies a ThmxTheme to the web. This involves elevating the web, which means the original web reference becomes stale. If any other feature receiver tries to make further changes to the web, an exception is thrown and the whole creation is rolled back.

At the moment, we seem to be successfully working around this by putting the ThmxTheme feature first in our feature stapler, which apparently makes the feature get activated last. I don't believe we can really rely on this.

The other way we could work around this problem is to change every feature receiver to get a clean web reference via ((SPWeb)properties.Feature.Parent).Site.OpenWeb. We don't have full control over all the features, though.

Ideally there'd be a way to refresh the single shared web reference at the end of the feature receiver that I know makes it stale, so none of the other features would have to be changed, but I don't believe this is possible.

Is there a canonical way of avoiding this problem? Can I really rely on the stapled features being activated bottom-to-top?

Was it helpful?

Solution

You should dispose of the SPWeb reference after each feature receiver has executed.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    using (SPWeb web = properties.Feature.Parent as SPWeb)
    {
    }
}

Admittedly, feature receivers such as this are one of the few places where you don't "have to" dispose of your SPWeb references in SharePoint, but in your case (and I had the same issue) this will ensure that each new feature loads a fresh up-to-date copy of the parent SPWeb.

http://solutionizing.net/2008/12/06/the-new-definitive-spsitespweb-disposal-article/

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top