Nest.js - Dependency Injection, Provider

크롱·2024년 10월 10일
0

Nest.js

목록 보기
2/15

Dependency?

예를들어 post랑 page에서 특정 user와 연결시키고싶을때 post/page class는 user class가 필요할것이다




dependency injection이 없다면 위 사진처럼 new User()을 각 class 안에서 세번 생성하겠지만


dependency injection을 통해 하나의 new User() 생성으로 여러 class에서 사용가능하당.
즉, new User() 가 필요한 곳에 주입(injection) 하면됨

Dependency injection 컨셉 이해하기

Dependency injection이 없다면..

이렇게 new User()을 계속 반복하게되는데

User was instantiated 가 두번출력되는걸 볼 수 있다.

Dependency injection 예시


constructor 부분을 new 대신 타입만 User로 지정

new User()은 한번만 지정해주고, 이를 constructor의 param으로 집어넣는다
그럼 사진 오른쪽처럼 User가 1번만 인스턴스화된걸 알수잇다!





Nest.js의 Dependency Injection

컨셉


User Instance 를 한번만 생성하고 다른 클래스가 필요할때마다 주입한다.

  • Module에서 다 관리한다
  • userController 에서 userService 를 사용하고싶다면 userModule에서 설정을 해줘야한다. 이때 userService는 provider가 된다.




이러한 디씨젼은 user module 에 의해 결정된다
만약 user service 를 post module에서 쓰고싶다면 export 해야됨



하우투 Injection ?

Providers?

@Injectable 데코레이터를 포함한 클래스들이 바로 Providers
즉, 이 데코레이터가 클래스를 비로소 provider로 만드는거다.

  • 프로바이더는 controller에서 비즈니스 로직을 operate 하기 위해 쓰인다
  • 보통 Module 파일에서 어떤 provider를 export할건지 결정한다. 즉, 모듈이 provider의 관리를 맡는다.

선언 (Declare)

  • @Injectable 데코레이터로 Provider를 선언한다

연결 (Connect)

  • module 파일에서 providers:[PROVIDER] 작성 -> 이제 이 provider는 해당 모듈에 포함된 파일에서 쓸수있다

주입 (Inject)

  • 보통 컨트롤러 파일에서 constructor(💖) 💖 이 부분에 provider 파일을 집어넣으면 주입 완성

    In order to tell Nestjs to inject this user service into our user's controller class, we need to use a constructor just the way we used it.
    And that's it with this one line of code. (pink line)
    Now user service class would be available to us instantiated inside the user's controller.



Controllers & Providers

I've been saying this time and again and I'll repeat it once more.
Controllers only hold the routing logic.
All the business logic need to be inside your provider classes.




꿀팁

nest g service posts/providers/posts --flat --no-spec




profile
👩‍💻안녕하세요🌞

0개의 댓글