Share via


How to: Get Services from the SharePoint Service Locator

This topic describes how to use a service that is managed by the SharePoint service locator. You must retrieve an instance of the implementation class that is registered for the interface.

The following services that are provided in the Microsoft.Practices.SPG.Common assembly are already registered with the SharePointServiceLocator class:

  • SharePointLogger. This is registered as an implementation of the ILogger interface.
  • TraceLogger. This is registered as an implementation of the ITraceLogger interface.
  • EventLogLogger. This is registered as an implementation of the IEventLogLogger interface.
  • HierarchicalConfig. This is registered as an implementation of the IHierarchicalConfig and IConfigManager interfaces.
  • ServiceLocatorConfig. This is registered as an implementation of the IServiceLocatorConfig interface.

To get an instance of a service

  1. In Visual Studio, add a reference to the SharePoint Guidance Library Microsoft.Practices.SPG.Common.dll and Microsoft.Practices.ServiceLocation.dll. If you are writing a feature receiver, item event receiver, workflow or anything else that needs to be in the global assembly cache, the Microsoft.Practices.SPG.Common and Microsoft.Practices.ServiceLocation assemblies also need to be in the global assembly cache.

  2. Retrieve the current SharePoint service locator using the Microsoft.Practices.SPG.Common.ServiceLocation.SharePointServiceLocator static class's Current property.

  3. Invoke the current service locator's GetInstance method with the interface as the type parameter.

    The following code demonstrates how to get an instance of the service.

    using Microsoft.Practices.ServiceLocation;
    using Microsoft.Practices.SPG.Common.ServiceLocation;
    
    IServiceLocator serviceLocator = SharePointServiceLocator.Current;
    
    // Get an instance of ILogger. 
    ILogger logger = serviceLocator.GetInstance<ILogger>();
    
    // Get an instance of a custom service registered to the
    // SharePoint service locator.
    ICustomService customService = serviceLocator.GetInstance<ICustomService>();
    

Home page on MSDN | Community site