Monday, October 25, 2010

Sharepoint Guidance Package - ServiceLocator

I recently took a look at the Sharepoint Guidance Package. The package supports Sharepoint developers by providing guidance and pre-defined components. Among these components you find the Service Locator, which can be used to register and find services within Sharepoint. A service may be any class. The Service Locator provides the ability to register types at SPSite and SPFarm level. Types are registered with their Interface used as key:
IServiceLocator serviceLocator = SharePointServiceLocator.GetCurrent();
IServiceLocatorConfig typeMappings =
serviceLocator.GetInstance<IServiceLocatorConfig>();
typeMappings.RegisterTypeMapping<IServiceInterface,IServiceImplementation>();
You can retrieve the instance of the Locator anytime by using a static method. Then you get the existing type mappings and add your own to it. You can have the same types on SPFarm and SPSite level. When searching for a type, the locator first searches at the current site and proceeds to the farm level, if no proper type was found.
You may retrieve a type the following way:
IServiceLocator serviceLocator = SharePointServiceLocator.GetCurrent();
ServiceImplementation service = serviceLocator.GetInstance<IServiceInterface>();
There's one thing you have to pay attention, when using the Service Locator and registering types. The Locator accesses the Sharepoint web application settings. To access these settings, it needs elevated privileges. So if you try to register types from within Webparts or controls, that are located on content sites, you will get a security exception. There are two workarounds for that. My preferred one is to use a Feature Receiver and overwrite the feature installed event. Just add an Event Receiver to the existing feature in your project or add a new feature.The installed event will be called, when the feature is installed on the Sharepoint site or farm, which requires an account with elevated privileges. So within the event you can do all your type registering without running in a security exception. The second workaround is to create a website inside the central administration. Have a look at Deploy an Application Page to Central Administration for that solution.

No comments:

Post a Comment