Share via


Retrieving Service Instances

When you use the SharePoint Service Locator, your most common task will be to retrieve a service instance. The SharePoint Service Locator lets you retrieve service instances in several different ways.

The most common way to retrieve a service instance is by calling the generic GetInstance method that corresponds to the required interface type. If more than one implementing class is registered to the specified interface type, the GetInstance method will return the implementing class that was most recently registered.

IService1 service1 = serviceLocator.GetInstance<IService1>();

When you register a service with the SharePoint Service Locator, you can optionally include a key string in each type mapping. This is useful if you have registered more than one implementing class against an interface, as it allows you to request a service by name as well as by interface. To do this, pass in the key string as a parameter to the GetInstance method.

IService2 service2 = serviceLocator.GetInstance<IService2>("alternate");

You may not always be able to use a strongly-typed GetInstance method if type mappings are not available at compile timeā€”for example, if no implementations of a particular interface have been registered when you develop your code. The GetInstance method provides overloads that allow you to specify interface types at run time.

IService3 service3 = (IService3)serviceLocator.GetInstance(typeof(IService3));

You can also use this approach to retrieve named mappings at run time.

IService4 service4 = (IService4)serviceLocator.GetInstance(typeof(IService4), 
   "alternate");

Finally, you can retrieve a collection of all the services registered for an interface type. The SharePoint Service Locator will instantiate each service and return an IEnumerable collection containing each object.

IEnumerable<IService5> services5 = serviceLocator.GetAllInstances<IService5>(); 

Similarly, you can retrieve a collection of all the services registered for an interface type by specifying the interface type at run time.

IEnumerable<object> services6 = serviceLocator.GetAllInstances(typeof(IService6));