Last active
June 15, 2022 07:27
-
-
Save tamanobi/7b6316e5cbed4f9a4cccdb8e9c879c0c to your computer and use it in GitHub Desktop.
inejctor の実験コード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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