Skip to content

Instantly share code, notes, and snippets.

@tamanobi
Last active June 15, 2022 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamanobi/7b6316e5cbed4f9a4cccdb8e9c879c0c to your computer and use it in GitHub Desktop.
Save tamanobi/7b6316e5cbed4f9a4cccdb8e9c879c0c to your computer and use it in GitHub Desktop.
inejctor の実験コード
from typing import Protocol
import injector
import os
class Repository(Protocol):
def get(id_: str) -> str: pass
def create(id_: str) -> str: pass
class RepoImpl(Repository):
def get(id_: str) -> str:
return "get_impl"
def create(id_: str) -> str:
return "create_impl"
class TestRepoImpl(Repository):
def get(id_: str) -> str:
return "[test] get_impl"
def create(id_: str) -> str:
return "[test] create_impl"
class Gateway(Protocol):
def get(self) -> list: pass
class Twitter(Gateway):
def get(self) -> list:
return []
class TestTwitter(Gateway):
def __init__(self, value) -> None:
super().__init__()
self.value = value
def get(self) -> list:
return ["test", self.value]
class TaskDIModule(injector.Module):
def configure(self, binder: injector.Binder) -> None:
binder.bind(Repository, to=RepoImpl)
binder.bind(Gateway, to=Twitter)
class TestTaskDIModule(injector.Module):
def configure(self, binder: injector.Binder) -> None:
binder.bind(Repository, to=TestRepoImpl)
binder.bind(Gateway, to=lambda: TestTwitter("foobar"))
class App:
@injector.inject
def __init__(self, repo: Repository, gw: Gateway) -> None:
self.repo = repo
self.gw = gw
def say(self):
print(self.repo.get())
print(self.gw.get())
def setup():
if os.environ.get("ENV", "test") == "test":
return injector.Injector([TestTaskDIModule()])
else:
return injector.Injector([TaskDIModule()])
if __name__ == "__main__":
container = setup()
app = container.get(App)
app.say()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment