Pages

Thursday, August 2, 2012

Lessons Learned Using the SharePoint Service Locator Pattern

Having wrestled with maintaining separate code bases for both SharePoint 2007 and 2010 I finally got to the point where I had some time to rethink strategy and that's when I came across Sohel's blog which explained a solution using the SharePoint Service Locator Pattern. Having just finished implementing this pattern I now can see some of the *huge* benefits, this approach provides. Here are a few:

  • Creating loose decoupling of code that is modular which enables a developer to make changes to dependencies without needing to recompile the existing code base. 
  • Easy write mocks and stubs for unit tests due to the dependency injection provided by the Service Locator 
  • Consolidation of repetitive code into a single code base 

After implementing this solution I wanted to list out some issues (work in progress) that I came across and how I fixed them:

Issue #1
SharePointServiceLocator.GetCurrent() threw a null reference exception

Solution to Issue #1
I was making calls to SharePointServiceLocator.GetCurrent() within the constructor of my application pages in SharePoint. For example, if I have a class named: MyClass, the constructor would look like:

public MyClass()
{
  SharePointServiceLocator.GetCurrent();
}

Moving the call, SharePointServiceLocator.GetCurrent(), to another location outside the constructor fixed the problem. Apparently the ServiceLocator instance is not instantiated until later in the page load cycle.

Issue #2
"Access Denied" error when registering mappings

Solution to Issue #2
This can happen when adding mappings at the Farm level (default setting for SP 2010 and the only option for SP 2007) in the SPWeb context. The solution is to create a Farm scoped feature and add register the mappings within the 'FeatureInstalled" event handler.

Issue #3
Type mappings are cleared from cache at the site collection level but not at the Farm level

Solution to Issue #3
Chris Keyser discussed this issue and a work around here: http://blogs.msdn.com/b/chriskeyser/archive/2011/01/20/handling-sharepointservicelocator-failures-due-to-caching.aspx

4 comments :

  1. your post are with coding of class thanks for this submission it's useful for me.

    ReplyDelete
  2. I finally got to the point where I had some time to rethink strategy and that's when I came across Sohel's blog which explained a solution using the SharePoint Service Locator Pattern.

    ReplyDelete
  3. About SharePoint Pattern information the very good stuff i like this please share other information.

    ReplyDelete
  4. This is good article for SharePoint developer as it addresses many issues and as an experience SharePoint developer author able to give best solutions for each discussed issues.

    ReplyDelete

I always welcome constructive feedback. Thanks.