본문 바로가기
ASP.NET Core

ASP.NET Core 6] Service - AddTransient, AddScoped, AddSingleton 차이점

by Fastlane 2022. 1. 17.
728x90
반응형

출처 : https://www.c-sharpcorner.com/article/understanding-addtransient-vs-addscoped-vs-addsingleton-in-asp-net-core/

 

아래 3 함수는 서비스의 lifetime을 지정한다. 

 

1. AddTransient : instance 요청 시마다 new instance가 생성된다. stateless service에 적합하다. 

                            multi-threading 시나리오에 가장 적합하다. 

2. AddScoped : 클라이언트 요청 당 한번 생성된다. 

                          동일한 클라이언트에 대해 같은 instance를 공유하고 싶을때 적합하다. 

3. AddSingleton : 처음 요청 시, 생성되고 이 후 요청 시, 동일한 instance를 사용한다. 

                            IoC container가 생성하고, app의 모든 requests와 함께 하나의 instance를 공유한다. 

 

Service Type
In the scope of a given http request
Across different http requests
Transient
New Instance
New Instance
Scoped
Same Instance
New Instance
Singleton
Same Instance
Same Instance
 
실습을 해보자. 
OperationService.cs
namespace Employee.Models
{

    
    public interface ITransientService
    {    
        Guid GetOperationID();
    }
    public interface IScopedService
    {
        Guid GetOperationID();
    }
    public interface ISingletonService
    {
        Guid GetOperationID();
    }

    public class OperationService : ITransientService, IScopedService, ISingletonService
    {
        Guid id;
        public OperationService()
        {
            id = Guid.NewGuid();
        }

        public Guid GetOperationID()
        {
            return id;
        }
    }
}
Program.cs
builder.Services.AddTransient<ITransientService, OperationService>();
builder.Services.AddScoped<IScopedService, OperationService>();
builder.Services.AddSingleton<ISingletonService, OperationService>();

HomeController.cs

        private readonly ILogger<HomeController> _logger;


        private readonly ITransientService _transientService1;
        private readonly ITransientService _transientService2;
        private readonly IScopedService _scopedService1;
        private readonly IScopedService _scopedService2;
        private readonly ISingletonService _singletonService1;
        private readonly ISingletonService _singletonService2;

        public HomeController(ILogger<HomeController> logger,
                    ITransientService transientService1,
                    ITransientService transientService2,
                    IScopedService scopedService1,
                    IScopedService scopedService2,
                    ISingletonService singletonService1,
                    ISingletonService singletonService2)
        {
            _logger = logger;
            _transientService1 = transientService1;
            _transientService2 = transientService2;
            _scopedService1 = scopedService1;
            _scopedService2 = scopedService2;
            _singletonService1 = singletonService1;
            _singletonService2 = singletonService2;
        }

        public IActionResult Index()
        {
            ViewBag.transient1 = _transientService1.GetOperationID().ToString();
            ViewBag.transient2 = _transientService2.GetOperationID().ToString();
            ViewBag.scoped1 = _scopedService1.GetOperationID().ToString();
            ViewBag.scoped2 = _scopedService2.GetOperationID().ToString();
            ViewBag.singleton1 = _singletonService1.GetOperationID().ToString();
            ViewBag.singleton2 = _singletonService2.GetOperationID().ToString();

            return View();
        }

Index.html

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>

    <div class="text-center">
        <h2 class="display-4">
            Dependency Injection Lifetime
        </h2>
    </div>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Service Type</th>
                <th>First Instance Operation ID</th>
                <th>Second Instance Operation ID</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td style="background-color: darksalmon">
                    Transient
                </td>
                <td style="background-color: darksalmon">
                    @ViewBag.transient1
                </td>
                <td style="background-color: darksalmon">
                    @ViewBag.transient2
                </td>
            </tr>
            <tr>
                <td>Scoped</td>
                <td>@ViewBag.scoped1</td>
                <td>@ViewBag.scoped2</td>
            </tr>
            <tr>
                <td style="background-color: aquamarine">
                    Singleton
                </td>
                <td style="background-color: aquamarine">
                    @ViewBag.singleton1
                </td>
                <td style="background-color: aquamarine">
                    @ViewBag.singleton2
                </td>
            </tr>
        </tbody>
    </table>
</div>
 

Request 1. 

 

Request 2. 

728x90
반응형

댓글