I've several repositories. To make them testable, I add the ORM session in the constructor.
class Repository: def __init__(session): self.session = session def save(object): self.session().query(object).save() class FruitRepository(Repository): def custom_method(): # ... pass
Problem: I need to inject the session every time I instantiate a repository. I'd like to have only one place in my code where the injection happens.
To clean things up I'd like to separate creation from usage:
from db import session def create_fruit_repository(): return FruitRepository(session) repository = create_fruit_repository()
It doesn't feel clean. Does anyone know a proper pattern to solve this issue? Maybe the factory pattern?
Further information: the application is a web scraper with several layers (loading, processing, analysing, reporting). It has some dependencies, but no framework. The application runs constantly as a services, not as a cronjob. Most is done on the command line, but it provides a REST-API.