Previously, we saw how we can use a Service Locator in order to prevent the 'newing' of objects in our code. However, everything comes with a price. We will talk about this in detail but to give you the gist of it, a service locator is an anti-pattern as it hides the class dependencies.
Commerce Application Example
The example we are following is from our last post. However, there are some modifications. For instance, we are not using any DI container to resolve the dependencies; rather, we are using a static Service Locator to do so.
public class Commerce
{
public void ProcessOrder(Order order)
{
decimal paidAmount = order.UnitPrice * order.Quantity;
bool paymentSuccessful = Locator.Resolve<PaymentProcessor>().ProcessPayment(paidAmount);
NotifyCustomer(paymentSuccessful);
}
private void NotifyCustomer(bool paymentSuccessful)
{
var notifier = Locator.Resolve<NotificationManager>();
if (paymentSuccessful)
{
notifier.NotifyCustomer("payment successful");
}
else
{
notifier.NotifyCustomer("payment failed");
Locator.Resolve<Logger>().Log("payment failed");
}
}
}
The Service Locator is used as a replacement for the new operator. That said, I have to admit this is no fancy locator, yet it serves the purpose and looks like this.
public static class Locator
{
private readonly static Dictionary<Type, Func<object>> services
= new Dictionary<Type, Func<object>>();
public static void Register<T>(Func<object> resolver)
{
services[typeof(T)] = resolver;
}
public static T Resolve<T>()
{
return (T)services[typeof(T)]();
}
}
While everything looks fine at first sight, there are some issues with our code. Let's explore them one after another.
Using Commerce API
Assume that in the Commerce class, we see something like the following in Visual Studio.
We can clearly infer that the Visual Studio IntelliSense won't indicate if Commerce itself has any dependencies. Rather, the developer gets the impression that he/she can create a Commerce object using its default constructor. Build the application, and it will surely be successful. But what happens at the run time is quite interesting.

Francis DoPosted Aug 13, 2019, 11:24 PM
Isn't the whole purpose of interface contract is to hide the implementation of the class?
Hamid KhanPosted Sep 29, 2017, 9:36 AM
Nice.............................................