Instantiate SPSite and SPWeb objects


I want to know whats the best method of Instantiating SPSite and SPWeb objects . As there are no. of ways by which you can do this.Some of the ways I know

SPSite mySite = SPControl.GetContextSite(Context);
            SPWeb myWeb = SPControl.GetContextWeb(Context);

//Why we use second method as in first method there is no need to write the hardcoded url and also no need to dispose too as recommended by Microsoft.

SPSite mySite=new SPSite("http://abc");
SPWeb myweb= mySite.RootWeb;

  or difff. way of disposing for it by having using( )


   3. Similar to first.. SPSite mySite = SPContext.Current.Site;
                         SPWeb myweb = SPContext.Current.Web;

Let me know if there is any other best approach or means out of these which should be the best approach to instantiate objects…..


Best Solution

You should do something like this:

using(SPSite oSPsite = new SPSite("http://server"))
    using(SPWeb oSPWeb = oSPSite.OpenWeb())
        // do stuff

You should also take a look into this: SharePoint Dispose Checker Tool, as it can inspect your code and to point where you're missing best practices.

EDIT: Yes, you can to use Context (and it's way I always do) but it shouldn't be used in some scenarios, like inside a SPSecurity.RunWithElevatedPrivileges. So, I recommend:

  • 1 method for normal operations
  • 2 for RunWithElevatedPrivileges and
  • 3 should not be used, as it probably will mess your request if disposed.
Related Question