Your simple python DI library built with good intentions.
pip install injkt
Good question.
from abc import ABC, abstractmethod
from injkt import Bind, Config, Injectable, Injktor, inject_args_deps
class IMailService(ABC):
@abstractmethod
def send_mail(self, subject: str, to: str) -> None:
...
class SmtpMailService(IMailService):
def send_mail(self, subject: str, to: str) -> None:
raise NotImplementedError()
injktor = Injktor(
Config(
{
Bind(IMailService, SmtpMailService),
}
)
)
@inject_args_deps
def business_logic(mail_service=Injectable(IMailService)):
mail_service.send_mail("Hello", "world")
business_logic()
from injktor import inject_attr_deps
@inject_attr_deps
class BusinessLogic:
mail_service = Injectable(IMailService)
def do_business_logic(self) -> None:
self.mail_service.send_mail("Hello", "world")
BusinessLogic().do_business_logic()
from injktor import InjktLazy
class BusinessLogic(InjktLazy):
mail_service = Injectable(IMailService)
def do_business_logic(self) -> None:
self.mail_service.send_mail("Hello", "world")
BusinessLogic().do_business_logic()
injktor = Injktor(
Config(
{
Bind(IMailService, SmtpMailService, always_reinit=True),
}
)
)
Enabling always_reinit
will re-initialize the dependency on each call.
NOTE: It won't be re-initialized in the same class if you aren't using InjktLazy