Blazor DI: Singleton, Scoped, Transient

정지효·2022년 12월 26일

DI-Dependency Injection (종속성 주입) : DI는 c#에서 클래스들끼리의 종속을 약하게 하고, 유닛테스트를 쉽게 하도록 한다.

public class NewsletterService
{
  private readonly IEmailService EmailService;

  public NewsletterService(IEmailService emailService)
  {
    EmailService = emailService;
  }

  public void SignUp(string emailAddress)
  {
     EmailService.SendEmail(...);
  }
}

위 코드에서 Line 3와 같이 작성된다.

종속성 주입에는 종류가 Singleton, Scoped, Transient 3가지가 있다.

각각의 차이를 쉽게 알기 위해 간단하게 난수를 출력하는 컴포넌트(DIcomponent.razor)를 제작하여 차이를 살펴보자.

  • Singleton: 두 개의 Request에 각각 생성된 Component에 동일한 난수가 생성됨

  • Scoped: Request에는 각각 다른 난수가, 각각 생성된 Component에는 동일한 난수가 생성됨

  • Transient: 두 개의 Request에 각각 생성된 Component에 모두 다른 난수가 생성됨

profile
백엔드 개발자

0개의 댓글