python/lagom

Lagom Dependency Injection

wefree 2023. 1. 16. 11:11

python dependency injection library 인 lagom 을 사용해 본다.

 

from abc import ABC

from lagom import Container, Singleton


class Base(ABC):
    def show(self):
        pass


class A(Base):
    def __init__(self) -> None:
        print('make a')

    def show(self):
        print('show a')


class A2(Base):
    def __init__(self) -> None:
        print('make a2')

    def show(self):
        print('show a2')


class B:
    def __init__(self, a: Base) -> None:
        print('make b')

    def show(self):
        print('show b')


class C:
    def __init__(self, base: Base, b: B) -> None:
        self.base = base
        self.b = b
        print('make c')

    def show(self):
        self.base.show()
        self.b.show()


def create_container() -> Container:
    container: Container = Container()

    container[B] = Singleton(B)  # B 를 만들기 위해서는 A 가 필요한데, 아직 A 는 정의되지 않은 상태임, 이렇게 순서 상관없이 정의 가능
    # container[B] = B(container[Base])
    # container[B] = lambda c: B(c[B]) # 호출할 때 마다 C 객체가 만들어 짐

    container[Base] = Singleton(A)
    # container[Base] = A()  # 이렇게 직접 A() 를 생성하면 eagarly 초기화 되므로 가능하면 이렇게 사용은 피하자?

    container[C] = Singleton(C)

    return container


def main():
    container: Container = create_container()
    container[C].show()


def test():
    container: Container = create_container()
    test_container = container.clone()
    test_container[Base] = A2()
    test_container[C].show()


if __name__ == '__main__':
    main()
    print("-------------------")
    test()

 

출력 결과

make a
make b
make c
show a
show b
-----------------------
make a2
make b
make c
show a2
show b