In my previous post Service Locator Pattern in C#: A Simple Example I introduced a fairly basic implementation of this pattern. In this post I will address one of the limitations of that implementation, introducing a form of lazy initialization.
Defining Lazy Initialization
Lazy initialization improves the performance of object creation, deferring long running initializations until they are really needed.
Suppose for example that some of the fields of an object need to be read from the database. If a client never access those fields, accessing the database to retrieve those fields has been useless and it has just made object initialization slower (often by a considerable factor).
Martin Fowler credits Kent Beck with the introduction of the lazy initialization pattern, and in PoEAA book he describes it in the following way:
The basic idea is that every access to the field checks to see if it's null. If so, it calculates the value of the field before returning the field. To make this work you have to ensure that the field is self-encapsulated, meaning that all access to the field, even from within the class, is done through a getting method.
The Improved Service Locator
The following is the improved version of the service locator which uses lazy initialization of the services.
We are now maintaining two separate maps:
servicesTypemaps an interface describing a service to a type T that implements that interface.
instantiatedServicesmaps an interface to an instantiated object of class T.
Both maps are initialized in the constructor. However only the first map is filled.
GetService is invoked, we check whether a concrete
implementation of that service has already been created. If not, we create that service
implementation retrieving its constructor via reflection, and we put a reference to that
implementation in the
For this to work, the service implementation needs to expose a default (parameterless) constructor.
If services creation time is significant, lazy initialization can save you quite some time during application start up, with very little cost in terms of increased complexity.
Next article in the series: A Singleton Service Locator