Jul 25, 2008 at 2:36 PM
Edited Jul 25, 2008 at 2:42 PM
Your createLookupColumn() method leaks a SPWeb instance when you call the RootWeb property. You'd better wrap it up in a using statement like this:
1: private static void createLookupColumn(SPWeb web, string sColumnDefinitionXml, string sColumnName)
3: // delete the column if it exists already and is not yet in use..
4: attemptColumnDelete(web, sColumnName);
6: SPFieldLookup lookupColumn = null;
8: // now create the column from the CAML definition..
9: string sCreatedColName = web.Fields.AddFieldAsXml(sColumnDefinitionXml);
11: lookupColumn = web.Fields.GetFieldByInternalName(sCreatedColName) as SPFieldLookup;
13: SPWeb rootWeb = web.Site.RootWeb;
16: lookupColumn.LookupWebId = rootWeb.ID;
21: // RootWeb might create a new SPWeb instance.
22: // Make sure it is disposed when necessary
23: if (rootWeb != web)
Most of the code examples use something like this that accomplishes the same thing...
using (SPWeb rootWeb = web.Site.RootWeb)
lookupColumn.LookupWebId = rootWeb.ID;
No, you must never use the using statement for disposing SPWeb instances obtained using the RootWeb property! This is because RootWeb doesn't always return a new SPWeb instance, but sometimes returns an existing instance. If you call Dispose on that instance,
you break other code. My special Dispose construct was the preferred way to deal with this. However, Microsoft released an updated advistory on how to deal with RootWeb via Roger Lambs blog:
What it comes down to is that you should never call Dispose on an SPWeb obtained from RootWeb. So my previous code sample shouldn't be used either.