Share via


Getting Services from the SharePoint Service Locator

Typical Goals

In this scenario, you want to use a service that is managed by the SharePoint service locator. You need to retrieve an instance of the implementation class that is registered for an interface.

Solution

In Visual Studio, add a reference to the SharePoint Guidance Library, Microsoft.Practices.SPG.Common.dll, and to Microsoft.Practices.ServiceLocation.dll. Retrieve the current SharePoint service locator using the Microsoft.Practices.SPG.Common.ServiceLocation.SharePointServiceLocator static class's Current property. Invoke the current service locator's GetInstance method with the interface as the type parameter.

Getting Services from the SharePoint Service Locator

The following code shows several ways to get a service from the SharePoint service locator.

using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.SPG.Common.ServiceLocation;

IServiceLocator serviceLocator = SharePointServiceLocator.Current;

// Get the default service.
IService1 service1 = serviceLocator.GetInstance<IService1>();

// Get a named service. 
IService2 service2 = serviceLocator.GetInstance<IService2>("alternate");

// Get the default service, with types specified at run time.
IService3 service3 = (IService3)serviceLocator.GetInstance(typeof(IService3));

// Get a named service, with types specified at run time.
IService4 service4 = 
            (IService4)serviceLocator.GetInstance(typeof(IService4), "alternate");

// Get a collection of all services registered for an interface type.
IEnumerable<IService5> services5 = serviceLocator.GetAllInstances<IService5>();

// Get a collection of all services registered for specified interface types
// with types specified at run time.
Type type1 = typeof(IService6);
IEnumerable<object> services6 = serviceLocator.GetAllInstances(type1);

Usage Notes

The GetInstance method of the SharePoint service locator either creates a new instance with every request or it uses a single shared instance for all requests. This behavior is set by an argument to the RegisterTypeMapping method of the ServiceLocatorConfig class.

Home page on MSDN | Community site