The GAC and the Service Locator solve different problems.
In your example, MyWebPart has an explicit reference you MyLogger.DLL. You are right, you could upgrade MyLogger.dll. But you could never plug in MyOtherLogger.dll that also has a ILogger implementation, without recompiling your MyWebPart.dll.
The GAC is a centralized repository that allows you to share Assemblies between applications. This has nothing to do with decoupling components of an application, which is the primary responsibilty of the servicelocator.
Now to answer your question, why would you need a service locator?
- You want to decouple your classes from their dependencies so that these dependencies can be replaced or updated with minimal or no changes to your classes' source code.
- You want to write classes that depend on classes whose concrete implementation is not known at compile time.
- You want to be able to test your classes in isolation, without using the dependencies.
- You want to decouple your classes from being responsible for locating and managing the lifetime of dependencies.
(from the Composite Application Guidance) http://msdn.microsoft.com/en-us/library/cc707905.aspx
Another excellent explaination why decoupling is useful is provided by the Unity dependency injection container (http://www.codeplex.com/unity):
Unity addresses the issues faced by developers engaged in component-based software engineering. Modern business applications consist of custom business objects and components that perform specific or generic tasks within the application, in addition
to components that individually address cross cutting concerns such as logging, authentication, authorization, caching, and exception handling.
The key to successfully building such applications is to achieve a decoupled or very loosely coupled design. Loosely coupled applications are more flexible and easier to maintain. They are also easier to test during development. You can mock up shims (lightweight mock implementations) of objects that have strong concrete dependencies; such as database connections, network connections, ERP connections, and rich user interface components.
Dependency injection is a prime technique for building loosely coupled applications. It provides ways to handle the dependencies between objects. For example, an object that processes customer information may depend on other objects that access the data store, validate the information, and check that the user is authorized to perform updates. Dependency injection techniques can ensure that the customer class correctly instantiates and populates all of these objects, especially where the dependencies may be abstract.
Hope this helps explaining why you would need a servicelocator.
Erwin van der valk
patterns & practices