서비스는 웹서버에서 서비스 로직의 역할을 하는 객체이다. 일반적으로 컨트롤러에서 호출되어, DB처리 등의 비지니스 로직을 처리후, 결과를 반환한다.
서비스를 생성하기 위해서는 일반적으로 다음과 같은 과정을 거친다
(IDE등을 이용해서) Service들을 담을 디텍토리 생성
서비스의 인터페이스 생성 - IProductService
서비스 생성 - ProductService
서비스의 라이프 타임을 고려하여 program.cs에 IProductService
에 ProductService
를 등록한다.
builder.Services.**AddScoped**<IProductService, ProductService>();
builder.Services.**Scoped**<IProductService, ProductService>();
builder.Services.**singleton**<IProductService, ProductService>();
사용할 컨트롤러에서 DI해서 사용.
public class TestController : ControllerBase
{
IProductService _product;
...
public TestController(IProductService product)
{
_product = product;
}
...
}
출처