How to Fix Service Locator Errors
In this tutorial, you'll learn about How to Fix Service Locator Errors. We cover key concepts, practical examples, and best practices.
Fix service locator errors when service dependencies hidden via global locator making testing impossible.
Quick Fix
Wrong
class ServiceLocator:
_services={}
@classmethod
def register(cls,name,impl): cls._services[name]=impl
@classmethod
def get(cls,name): return cls._services[name]()
class ReportService:
def __init__(self):
self.db=ServiceLocator.get('db') # hidden dependency!
def run(self): self.db.query()
Dependencies hidden. Impossible to know what ReportService needs without reading code. Tests need global locator setup.
Right
from abc import ABC,abstractmethod
class Database(ABC):
@abstractmethod
def query(self): pass
class ReportService:
def __init__(self,db: Database): # explicit dependency!
self.db=db
def run(self): self.db.query()
# Locator only at entry point:
class AppContainer:
def __init__(self):
self.db=SQLiteDB()
self.report=ReportService(self.db)
container=AppContainer(); container.report.run()
Dependencies explicit in constructor. Service Locator only at composition root.
Prevention
Service Locator provides global registry. Only use at composition root. Prefer dependency injection.
DodaTech Tools
Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro