1

I am developing a custom webpart. I have for example this method.

private void DeactivateProvisioningFeature()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        site.AllowUnsafeUpdates = true;
                        web.AllowUnsafeUpdates = true;
                        web.Update();

                        // remove feature if exist
                        if (site.Features[provisioningFeatureId] != null)
                        {
                            site.Features.Remove(provisioningFeatureId);
                        }

                        site.AllowUnsafeUpdates = false;
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });
        }

What is wrog with this row? Someone told me I do not need to implement the using on the site.RootWeb. Can someone explain please?

using (SPWeb web = site.RootWeb)

1
2

The rules for when to Dispose SharePoint object unfortunately aren't simple.

The overall principle is that object use create using new or by enumerating should be disposed and object which are simple references from an existing should be left alone.

But as this is SharePoint development (and if it was easy everybody could do it) there is a number of exception to this.

So you must read Best Practices: Using Disposable Windows SharePoint Services Objects even though it states to be for old version it still relevant.

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.