공부/기타
[웹 서버] singleton, transient, scoped 생명주기 비교
돌멩이수프
2022. 7. 23. 13:25
728x90
.NET에서 종속성을 주입할 때 사용하는 3가지 서비스의 생명주기를 비교해보자.
기본 Blazor.Server의 프로그램을 조금만 수정하면 생명주기를 쉽게 알 수 있다.
Data에 Test.cs 파일을 생성해준다.
using System;
namespace BlazorApp1.Data
{
public class Test
{
}
public class SingletonService : IDisposable
{
public Guid ID { get; set; }
public SingletonService()
{
ID = Guid.NewGuid();
}
public void Dispose()
{
Console.WriteLine("SingletonService Disposed");
}
}
public class TransientService : IDisposable
{
public Guid ID { get; set; }
public TransientService()
{
ID = Guid.NewGuid();
}
public void Dispose()
{
Console.WriteLine("TransientService Disposed");
}
}
public class ScopedService : IDisposable
{
public Guid ID { get; set; }
public ScopedService()
{
ID = Guid.NewGuid();
}
public void Dispose()
{
Console.WriteLine("ScopedService Disposed");
}
}
}
Pages에 index.razor파일을 고쳐준다.
@using BlazorApp1.Data;
@inject SingletonService singleton;
@inject TransientService transient;
@inject ScopedService scoped;
<div>
<h1>Singleton</h1>
Guid: @singleton.ID
<h1>Transient</h1>
Guid: @transient.ID
<h1>Scoped</h1>
Guid: @scoped.ID
</div>
가장 중요한! startup.cs 안 ConfigureServices에 내용을 추가해준다.
services.AddSingleton<Test>();
services.AddSingleton<SingletonService>();
services.AddTransient<TransientService>();
services.AddScoped<ScopedService>();
영상을 살펴보자.
1️⃣ Singleton
새로고침, 다른 페이지로 이동에 아무 상관 없이 숫자가 변하지 않는다.
즉, 클라이언트의 접속에 상관 없이 서비스가 시작할 때 생성된 후로 변하지 않는다. 클라이언트의 수에 관계 없이 하나의 서비스만 존재한다.
2️⃣ Transient
새로고침, 다른 페이지로 이동 모두 숫자가 변한다.
즉, 클라이언트의 모든 움직임마다 서비스가 새로 생성된다.
3️⃣ Scoped
새로고침에는 숫자가 변하지만 다른 페이지로 변할 때는 숫자가 변하지 않는다.
클라이언트의 새로운 요청이 있는 동안에만 유지된다. 각 클라이언트마다 하나씩 서비스가 존재한다.
728x90