Share via


The SharePoint Service Locator

The SharePoint Guidance Library includes an implementation of the service locator pattern named the SharePoint service locator. The SharePoint service locator is a reusable component that you can include in your own SharePoint applications. It allows you to decouple consumers of an interface from the implementations of that interface. Instead of creating an object by invoking the constructor of a class, you request an object with a specified interface from the service locator. Decoupling your code from a concrete implementation makes your code easier to test and more modular. For more information about the Service Locator pattern, see Service Locator Pattern.

Components that provide implementations of interfaces can register those implementations with the SharePoint service locator. A SharePoint feature that provides a specific implementation typically registers the implementation with the service locator in its feature receiver.

Internally, the SharePoint service locator has a dictionary that maps an interface and an optional key string to the name of a class that implements the specified interface. The following table illustrates this. Each row in the table is a type mapping.

Interface

Registered implementation class

ILogger

SharePointLogger

IProductCatalogRepository

ProductCatalogRepository

For example, suppose that at run time you need to find a service that supports the ILogger interface. You invoke the service locator and the service locator responds by looking up a matching implementation class in its table of type mappings. By default, the corresponding implementation class is SharePointLogger.

The SharePointServiceLocator class provides access to a single service locator instance that is used by all application components. This instance implements the IServiceLocator interface from the Common Service Locator project. By default, the SharePointServiceLocator.Current property returns an implementation of IServiceLocator that is based on the ActivatingServiceLocator class. It is also possible to substitute other service locator implementations, such as the Microsoft patterns & practices Unity Dependency Injection container.

This section includes the following topics:

Home page on MSDN | Community site