Question: Possible to have "named" instances
Hi there, first of all thanks for providing a great project here, coming from c# background, its been the backbone of all of my python projects so far.
At the moment I have a bit of an interesting problem to resolve and wondering if this is possible. I have created a service layer project which takes a database object, which normally i just inject etc.
However for this new project, I have to show an overall system, that talks to two of these databases, each for a different company, but they have the same structure.
Since I have it separated out as a service project layer, I'm struggling to see how I can inject in my singleton database objects. ( two different ones) and how to differentiate when I want to talk to database a or database b.
Any Ideas?
Thanks
Hey, good to hear you're finding the project useful. As far as your question is concerned something like this comes to mind (apologies if I misunderstood the injection direction here):
import injector
class Database:
def __init__(self, uri: str) -> None:
self.uri = uri
class RegularDatabase(Database): pass
class BonusDatabase(Database): pass
class Service:
@injector.inject
def __init__(regular: RegularDatabase, bonus: BonusDatabase) -> None:
self.regular = regular
self.bonus = bonus
def configure(binder: injector.Binder) -> None:
binder.bind(RegularDatabase, to=RegularDatabase('regular uri'), scope=injector.singleton)
binder.bind(BonusDatabase, to=BonusDatabase('bonus uri'), scope=injector.singleton)
my_injector = injector.Injector([configure])
# ...
There are other approaches I can think of (like using Key or other placeholders) but this one provides a degree static type safety (if used with tools like mypy). Subclassing Database is completely artificial in this example but that's what's required to make it work nicely (see https://github.com/alecthomas/injector/issues/56 for related discussion)