How to: Register a Service

The following procedure demonstrates how you can use the SharePoint Service Locator to register a class as the implementation of an interface.

To register a service with the SharePoint Service Locator

  1. Add assembly references to Microsoft.Practices.SharePoint.Common.dll and Microsoft.Practices.ServiceLocation.dll.

  2. Add the following using statements to the top of your source code file.

    using Microsoft.Practices.ServiceLocation;
    using Microsoft.Practices.SharePoint.Common.ServiceLocation;
    
  3. Declare an object of type IServiceLocator and set it to the value of the SharePointServiceLocator.Current property.

    IServiceLocator serviceLocator = SharePointServiceLocator.GetCurrent();
    
  4. Use the service locator to request an implementation of the IServiceLocatorConfig interface. The returned object contains the type mappings that are managed by the service locator.

    Note

    If you want to scope your type mapping to a site collection, you must also set the Site property on the IServiceLocatorConfig instance.

    IServiceLocatorConfig typeMappings =  
     serviceLocator.GetInstance<IServiceLocatorConfig>();
    
  5. Call the IServiceLocator.RegisterTypeMapping method. The first type parameter is the interface that you are implementing, and the second type parameter is your implementation class.

    typeMappings.RegisterTypeMapping<IService1, Service1>();