WithWeb-pattern of Jonas Nilsson
By Anatoly Mironov
Jonas Nilsson shows an interesting approach for working with SPSite and SPWeb which must be disposed. Create a helper method WithWeb and send an Action parameter:
public void WithWeb(string uri, Action<SPWeb> action)
{
using (SPSite site = new SPSite(uri))
{
using (SPWeb web = site.OpenWeb())
{
action(web);
}
}
}
```Here is my implementation of this pattern:
public static class DisposalService { public static void WithWeb(string uri, Action action) { using (var site = new SPSite(uri)) { using (var web = site.OpenWeb()) { web.UnsafeUpdate(action); } } } public static void WithElevatedWeb(string uri, Action action) { SPSecurity.RunWithElevatedPrivileges(() => WithWeb(uri, action)); } }
Action update = (SPWeb w) => { UserService.UpdateOwners(owners, w); UserService.UpdateMembers(members, w); }; DisposalService.WithWeb(SPContext.Current.Web.Url, update);