Service Locator Pattern in C#: A Simple Example
A Service Locator is a common design pattern that allows decoupling clients of services (described by a public interface) from the concrete class implementing those services. Martin Fowler has a great introduction on the topic in his Inversion of Control Containers and the Dependency Injection pattern.
What follows is a very simple service locator implementation in C# based on generics.
Let's start defining the contract of a service locator.
Now let's see a very simple implementation of this contract:
As you can see,
- the constructor of the class registers all the available services in a dictionary.
In our example, we have 3 different services accessible through
IServiceA
,IServiceB
, andIServiceC
. It is assumed here thatServiceA
implementsIServiceA
and so forth. - the generic GetService() method returns a reference the correct implementation fetching it from the dictionary
This is how a client would invoke the service:
The clients do not know the actual classes implementing the service. They only have to interact with the service locator to get to an implementation.
Improvements
This is as simple as it gets. There are several improvements that a real-world implementation of a service locator should consider (what follows is only a partial list):
- The service locator itself might be a singleton. There usually is no need to have two instances of a service locator.
- Lazy initialization of services might be considered. In the example above, the constructor creates new instances for all possible services; initialization might be deferred until some client actually requests a particular service.
- The mapping between interfaces and implementation might be more flexible using metadata (e.g. through application configuration files)
Next article in the series: Service Locator Pattern in C# with Lazy Initialization
Leave a Comment