Replacing the Current Service Locator

Typical Goals

In this scenario, you want to provide a custom environment for unit testing. You have stub implementations of a service your component uses and you want to register the stub implementations with a service locator. This scenario may not require a full SharePoint context at runtime.


In Visual Studio, add a reference to the SharePoint Guidance Library, Microsoft.Practices.SPG.Common.dll. Create an instance of the Microsoft.Practices.SPG.Common.ServiceLocation.ActivatingServiceLocator class and invoke its RegisterTypeMapping method. Use the interface and the implementation class you want your application class to use at run time as type parameters to the RegisterTypeMapping method. Call the ReplaceCurrentServiceLocator static method of the Microsoft.Practices.SPG.Common.ServiceLocation.SharePointServiceLocator class to set the current service locator.


For an extended example of how to replace the current SharePoint service locator, see [TBD].

Replacing the Current SharePoint Service Locator

The following code shows an example of a unit testing initialization method that replaces a configured service with a test-specific class.
public class PricingFixture
   private MockSecurityHelper mockSecurityHelper;

   public void Init()
       ActivatingServiceLocator serviceLocator = new ActivatingServiceLocator();



       this.mockSecurityHelper = 
            as MockSecurityHelper;

   public void Cleanup()

Usage Notes

It is recommended that you use ReplaceCurrentServiceLocator to set the service locator to null as part of the unit test's cleanup step. This allows the default SharePoint service locator to be restored for subsequent tests.

Passing the InstantiationType.AsSingleton enumerated value as an argument to the RegisterTypeMapping method allows you to specify that a single instance of the implementation class is used for all service location requests. This is important in the unit-testing scenario because you typically want to set test-specific properties of the mock object that your test environment provides. By default, the ActivatingServiceLocator class creates a new instance with each service location request.

Note: In the unit testing scenario, it is important to replace the current SharePoint service locator before you attempt to get the value of the SharePointServiceLocator.Current static property. The reason for this is that instantiating the default SharePoint service locator requires you to be running in a SharePoint context, which may not be the case when performing a unit test. By replacing the current service locator before evaluating the SharePointServiceLocator.Current property, you can avoid a runtime dependency on the SharePoint environment.

To give feedback.
Copyright (c) 2007 by Microsoft Corporation. All rights reserved.

Last edited Jun 16, 2009 at 2:49 PM by ckeyser, version 1


No comments yet.