I have several services that use the SPWeb object. These services are called to perform various functions, sometimes completely unrelated. i.e. an AuthenticationService uses SPWeb to get information about the user. I have a LibraryService that uses SPWeb to get information from SharePoint lists.

Either SPWeb needs to be passed around as an argument somehow to these services, or each method needs to instantiate it's own SPWeb object.

        using (SPSite siteCollection = new SPSite("http://site"))
            using (SPWeb web = siteCollection.OpenWeb())

I'm trying to see what the best practice is for using the SPWeb across these services. The two options that I can think of are to pass around the SPWeb object, or to initialize the SPWeb in each method of the service that needs to use it.

Even though passing SPWeb might alleviate the issue at the surface, and save a bit on cpu/ram resources, it seems like bad practice.

  • It's bad practice to make SPWeb part of the method signature, just because the implementation of that method needs it. Makes for bad interfaces.
  • What if a method needs to run SPWeb under elevated privileges? The whole purpose of passing SPWeb to that method is then moot.

So is instantiating SPWeb in each method the way to go?

SharePoint 2013, on-premise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.