I'm using the injector module that embodies most of the Guice API for a DI framework.
What I am trying to accomplish what Guice does with the @Named binding annotation. That is to say, using the injector.Module
to override the configure
method and use the Binder to bind multiple instances of the same type, but with different names:
import pathlib
import injector
ConfigFile = pathlib.WindowsPath
UserFile = pathlib.WindowsPath
cfg_file = pathlib.Path.home() / 'settings.cfg'
usr_file = pathlib.Path.home() / 'user.inf'
class AppModule(injector.Module):
def configure(self, binder):
binder.bind(ConfigFile, to=cfg_file) # Guice uses annotatedWith here
binder.bind(UserFile, to=usr_file) # Guice uses annotatedWith here
class App:
@injector.inject
def __init__(self, cfg: ConfigFile, usr: UserFile):
self.config = cfg
self.user = usr
app = injector.Injector(AppModule).get(App)
print(app.config, app.user) # prints the contents of `usr_file` for both
I thought that Binder.multibind my have some viability, but I've been unsuccessful in my attempts. They only solution I can devise is one in which pathlib.Path
must be subclassed and those subclasses explicitly bound to their instances (which can be manged in the injector.Module
using @provider in conjunction with @singleton).
Is there another way to accomplish this that does not resolve to sublcasses?