Fastapi 의존성 주입

codakcodak·2024년 3월 25일
0

fastapi

목록 보기
2/2
post-thumbnail

의존성 주입

  • 다양한 클래스나 함수 간의 강한 결합을 줄이기 위해 사용되는 기술
  • 의존성을 사용하는 컴포넌트가 직접 정하는 것이 아니라 외부에서 전달(주입)
  • injector라고 불리는 별도의 모듈에서 관리

다양한 용어들

  • Coupling(결합)-강하게 결합된 컴포넌트들은 수정과 변경이 어려움
  • Dependency(의존성)-한 컴포넌트가 올바르게 동작하기 위해 다른 요소에 의존하는 것

Coupling의 단점

기존코드

class Body:
    def __init__(self,color):
        self.color=color
    
class Car:
    def __init__(self):
        self.body=Body(color='red')
    
    def drive(self):
        pass

#Car라는 인스턴스를 만든다면 항상 명시된 red속성으로밖에 만들지 못하여 추후 수정에 불리하다.
red_car=Car()

의존성 주입 코드

class Body:
    def __init__(self,color):
        self.color=color
    
class Car:
    def __init__(self,body):
        self.body=body
    
    def drive(self):
        pass

#실제로 필요한 컴포넌트나 클래스를 외부에서 선언하고 직접 주입
red_car=Car(body=Body(color="red"))
blue_car=Car(body=Body(color="blue"))

Depends

  • fastapi가 제공하는 Dependency Injection

Depends 적용 전

Depends 적용

Repository Pattern

  • 데이터를 다루는 부분을 추상화하는 기술로 비지니스 로직과 데이터 관리의 강한 결합을 없애준다.
  • 데이터를 불러오고 저장하는 것과 같은 구체적인 구현은 감춘다.

profile
숲을 보는 코더

0개의 댓글