There are multiple ways to work in the SP object model. The starting point for instantiating objects looks different when you look at different developers.
Many times I see people doing this:
SPList myList = SPContext.Current.Web.GetList("MyList");
SPWorkflowAssociation myWorkflowAssociation = SPContext.Current.Web....
so basically they are using multiple "SPContext.Current
". I would assume this is not best practice and one should do multiple SPContext.Current within a using
block?! Of course we should create our own object then, otherwise we would dispose the current web, so we should do this:
using (SPSite siteCollection = new SPSite(SPContext.Current.Web.Url))
instead of this:
using (SPWeb currentWeb = SPContext.Current.Web) //do not do this
Am I correct this far?
Furthermore I sometimes think that using SPContext.Current
in general might be dangerous once you don't know your code will always be executing in the SharePoint context. I'm thinking of activating a feature via Powershell or running unit tests via little console applications (both no SPContext.Current
!).
Would it then be "correct" to use the following?
using (SPWeb currentWeb = new SPWeb(<Url from some config file>)
Microsoft uses SPContext.Current here: Getting References to Sites, Web Applications, and Other Key Objects and also in their Disposing Objects article from the SP2010 Best Practices (very good read btw). But at the same time they use the aforementioned method of using a URL from somewhere to instantiate the objects instead of using SPContext.Current.
Would I be correct to assume the following rules:
- Instead of multiple instantiations of Sharepoint objects, make use of
using
blocks to properly dispose objects after usage - Do not dispose objects you didn't create (i.e.
SPContext.Current.Web
) - Use
SPContext.Current
when you know your code is running in SharePoint, when not sure use a static URL (or something else) to instantiate SP objects.