Share via


How to: Register Services with the SharePoint Service Locator

The following procedure describes how to register a service with the SharePoint service locator.

To register 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. Create a feature receiver class and add code to the FeatureInstalled method that does the following:

    • Uses the Microsoft.Practices.SPG.Common.ServiceLocation.SharePointServiceLocator static class's Current property to retrieve the current SharePoint service locator
    • Uses the current SharePoint service locator to get an instance of the IServiceLocatorConfig interface
    • Uses the instance of the IServiceLocatorConfig interface to register the service type and interface type

    The following code demonstrates how to perform this step.

    using Microsoft.SharePoint;
    using Microsoft.Practices.ServiceLocation;
    using Microsoft.Practices.SPG.Common.ServiceLocation; 
    
    [CLSCompliant(false)]
    [Guid("<Your feature GUID>")]
    public class MyFeatureReceiver : SPFeatureReceiver
    { 
        /// ...
    
        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
           // Get the ServiceLocatorConfig service from the service locator.
           IServiceLocator serviceLocator = SharePointServiceLocator.Current;
           IServiceLocatorConfig serviceLocatorConfig =  
                                     serviceLocator.GetInstance<IServiceLocatorConfig>();
    
           serviceLocatorConfig.RegisterTypeMapping<IMyService, MyService>();
        }   
    } 
    

The FeatureInstalled method is called when the feature is installed on a Web front-end server. The service registration is stored in the SPFarm object's property bag and the application pool is recycled. This forces the SharePointServiceLocator instance to reload its type mappings from the ServiceLocatorConfig instance.

Home page on MSDN | Community site