Thursday, August 19, 2010

SharePoint Service Locator: Register Singleton Type

In my previous post I have described how to register type with SharePoint Service Locator. Today I’ll explain how to register singleton instance. We usually use Feature Receiver to register types. The following code snippet shows how to register singleton instance.

public class ServiceLocatorFeatureEventReceiver : SPFeatureReceiver
{
    public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        var currentSite=properties.Feature.Parent as SPSite;
        var serviceLocator = SharePointServiceLocator.GetCurrent();
        var typeMapper = serviceLocator.GetInstance<IServiceLocatorConfig>();
        typeMapper.Site = currentSite;
        typeMapper.RegisterTypeMapping<INonsingletonInterface, NonsingletonType>();
        
        var singletonTypeMapper = typeMapper as ServiceLocatorConfig;
        singletonTypeMapper.RegisterTypeMapping<ISingletonInterface, SingletonType>(null, InstantiationType.AsSingleton);

        SharePointServiceLocator.Reset();
    }


    public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
    {
        var currentSite=properties.Feature.Parent as SPSite;
        var serviceLocator = SharePointServiceLocator.GetCurrent();
        var typeMapper = serviceLocator.GetInstance<IServiceLocatorConfig>();
        typeMapper.Site = currentSite;
        typeMapper.RemoveTypeMapping<INonsingletonInterface>(null);

        var singletonTypeMapper = typeMapper as ServiceLocatorConfig;
        singletonTypeMapper.RemoveTypeMapping<ISingletonInterface>(null);

        SharePointServiceLocator.Reset();
    }
}

As shown in above code block, to register singleton instance, you need to cast the IserviceLocatorConfig instance to ServiceLocatorConfig. Then you can specify the InstantiationType.AsSingleton for registering the type as singleton.

 

When you register a type as singleton, on first request the type will be instantiated and for later requests the instance created on first request will be delivered. However, if IIS is reset then the instance will be destroyed and create anew on first request.

2 comments:

  1. In your code example above, where are you getting "serviceLocatorconfig" from in the line:
    var singletonTypeMapper = serviceLocatorconfig as ServiceLocatorConfig;

    ReplyDelete
  2. Sorry, the statement should be 'var singletonTypeMapper = typemapper as ServiceLocatorConfig'. And the "ServiceLocatorConfig" variable should be typemaper. I've updated the post. Thanks for observation.

    ReplyDelete