Asp.Net Core 에서 서비스의 생명주기 옵션 차이 와 용법 에 대한 상세 한 설명
최근 에 작은 Demo 를 만 들 때 한 인터페이스 에서 보기 구성 요 소 를 두 번 호출 하고 보기 구성 요소 에서 데이터 베 이 스 를 호출 하여 조회 한 결과 오류 가 발생 했 습 니 다.두 보기 구성 요소 의 호출 을 분리 시 키 고 단독으로 진행 하 였 으 나 정상 적 인 것 을 찾 았 습 니 다.주입 서비스 에 의존 하 는 설정 을 발 견 했 을 때 서비스의 수명 주기 가 적절하게 설정 되 지 않 아서이에 따라 세 사람 사이(심지어 네 사람 사이 의 용법 과 차이)를 인식 하 는 실험 을 한다.
본문 demo 주소(구체 적 으로 WebApi 컨트롤 러 참조):https://gitee.com/530521314/koInstance.git ( 로 컬 다운로드 )
1.서비스의 생명주기
Asp.Net Core 에서 내 장 된 용 기 는 서비스의 생명 주 기 를 관리 하 는 것 을 책임 집 니 다.주입 용기 에 의존 하여 생 성 되 는 것 부터 시작 하여 우리 가 서 비 스 를 호출 할 때 용기 가 이 서비스의 모든 실력 을 방출 할 때 까지 몇 가지 형식 으로 표 현 됩 니 다.
1.Transient:서 비 스 를 요청 할 때마다 새로운 인 스 턴 스 를 만 듭 니 다.이러한 생명 주 기 는 경량급 서비스(예 를 들 어 Repository 와 ApplicationService 서비스)에 적합 합 니 다.
2.Scoped:모든 HTTP 요청 에 인 스 턴 스 를 만 들 고 수명 주기 가 전체 요청 을 관통 합 니 다.
3.SingleTon:첫 번 째 서 비 스 를 요청 할 때 이 서 비 스 를 위해 인 스 턴 스 를 만 든 다음 에 요청 할 때마다 첫 번 째 서 비 스 를 사용 합 니 다.
4.인 스 턴 스:싱글 톤 과 유사 하지만 프로그램 이 시 작 될 때 이 인 스 턴 스 를 용기 에 등록 합 니 다.싱글 톤 보다 먼저 존재 한 다 는 뜻 으로 이해 할 수 있 습 니 다.
응용 프로그램 에서 관련 서비스의 생명 주 기 를 제어 하 는 방법 은 해당 하 는 add*를 통 해 다음 과 같은 세 가지 로 지정 합 니 다.물론 확장 방법 을 통 해 ConfigurationServices 방법 에서 보 이 는 코드 수량 을 간소화 할 수 있 습 니 다.
services.AddTransient<IApplicationService, ApplicationService>();
services.AddScoped<IApplicationService, ApplicationService>();
services.AddSingleton<IApplicationService, ApplicationService>();우선 서비스 와 관련 된 조작 인 터 페 이 스 를 설계 하 다.
public interface IOperation
 {
 Guid GetGuid();
 }
 public interface IOperationTransient: IOperation
 {
 }
 public interface IOperationScoped : IOperation
 {
 }
 public interface IOperationSingleton : IOperation
 {
 
 }
 public interface IOperationInstance : IOperation
 {
 
 }
      
/// <summary>
 ///     
 /// </summary>
 public class Operation : IOperation
 {
 private readonly Guid _guid;
 public Operation()
 {
 _guid = Guid.NewGuid();
 }
 public Operation(Guid guid)
 {
 _guid = guid == Guid.Empty ? Guid.NewGuid() : guid;
 }
 public Guid GetGuid()
 {
 return _guid;
 }
 }
 /// <summary>
 ///     
 /// </summary>
 public class OperationTransient : IOperationTransient
 {
 private readonly Guid _guid;
 public OperationTransient()
 {
 _guid = Guid.NewGuid();
 }
 public OperationTransient(Guid guid)
 {
 _guid = guid == Guid.Empty ? Guid.NewGuid() : guid;
 }
 public Guid GetGuid()
 {
 return _guid;
 }
 }
 /// <summary>
 ///          
 /// </summary>
 public class OperationScoped : IOperationScoped
 {
 private readonly Guid _guid;
 public OperationScoped()
 {
 _guid = Guid.NewGuid();
 }
 public OperationScoped(Guid guid)
 {
 _guid = guid == Guid.Empty ? Guid.NewGuid() : guid;
 }
 public Guid GetGuid()
 {
 return _guid;
 }
 }
 /// <summary>
 ///          
 /// </summary>
 public class OperationSingleton : IOperationSingleton
 {
 private readonly Guid _guid;
 public OperationSingleton()
 {
 _guid = Guid.NewGuid();
 }
 public OperationSingleton(Guid guid)
 {
 _guid = guid == Guid.Empty ? Guid.NewGuid() : guid;
 }
 public Guid GetGuid()
 {
 return _guid;
 }
 }
 /// <summary>
 ///          
 /// </summary>
 public class OperationInstance : IOperationInstance
 {
 private readonly Guid _guid;
 public OperationInstance()
 {
 _guid = Guid.NewGuid();
 }
 public OperationInstance(Guid guid)
 {
 _guid = guid == Guid.Empty ? Guid.NewGuid() : guid;
 }
 public Guid GetGuid()
 {
 return _guid;
 }
 }
        
public interface IOperationService
 {
 /// <summary>
 ///        Guid 
 /// </summary>
 /// <returns></returns>
 List<string> GetGuidString();
 }
      
/// <summary>
 ///     
 /// </summary>
 public class OperationService : IOperationService
 {
 public IOperationTransient _transientOperation { get; }
 public IOperationScoped _scopedOperation { get; }
 public IOperationSingleton _singletonOperation { get; }
 public IOperationInstance _instanceOperation { get; }
 public OperationService(IOperationTransient transientOperation,
 IOperationScoped scopedOperation,
 IOperationSingleton singletonOperation,
 IOperationInstance instanceOperation)
 {
 _transientOperation = transientOperation;
 _scopedOperation = scopedOperation;
 _singletonOperation = singletonOperation;
 _instanceOperation = instanceOperation;
 }
 public List<string> GetGuidString()
 {
 return new List<string>()
 {
 $"Transient:"+_transientOperation.GetGuid(),
 $"Scoped:"+_scopedOperation.GetGuid(),
 $"Singleton:" +_singletonOperation.GetGuid(),
 $"Instance:"+_instanceOperation.GetGuid(),
 };
 }
 }
       
[Route("api/[controller]")]
 [ApiController]
 public class ValuesController : ControllerBase
 {
 private readonly IOperationService _operationService;
 public ValuesController(IOperationService operationService)
 {
 _operationService = operationService;
 }
 [HttpGet]
 [Route(nameof(GetGuidString))]
 public ActionResult<string> GetGuidString()
 {
 return string.Join("
", _operationService.GetGuidString());
 }
 }
services.AddTransient<IOperationTransient, OperationTransient>();
services.AddScoped<IOperationScoped, OperationScoped>();
services.AddSingleton<IOperationSingleton, OperationSingleton>();//             
services.AddSingleton<IOperationInstance>(new OperationInstance(Guid.Empty));
services.AddTransient<IOperationService, OperationService>();첫 번 째 시작 프로그램(닫 지 않 음)접근:
 
   두 번 째(첫 번 째 기초 위 에서 재 방문)방문:
 
   이 를 통 해 알 수 있 듯 이 두 번 의 방문 에서 Singleton 과 Instance 는 똑 같 습 니 다.모두 응용 프로그램 이 시 작 될 때 와 응용 서비스 로 딩 할 때 결 정 됩 니 다.Singleton 은 서비스 에 처음 들 어 갈 때 분 배 를 하고 변 하지 않 습 니 다.인 스 턴 스 는 응용 프로그램 이 시 작 될 때 인 스 턴 스 를 주입 하고 서비스 에 들 어 갈 때 도 최초의 인 스 턴 스 를 유지 하 며 인 스 턴 스 를 재배 치 하지 않 았 습 니 다.트 랜 짓 과 Scoped 는 달 라 졌 다.
프로그램 종료,재 부팅,세 번 째 접근:
 
   볼 수 있 듯 이 싱글 턴 과 인 스 턴 스에 변화 가 생 겼 고,그 간 싱글 턴 과 인 스 턴 스에 적 었 던 역할 도 설명 한다.
그 다음 에 Transient 와 Scoped 의 차이 점 을 디자인 하기 시 작 했 습 니 다.기 존 코드 에 새로운 기능 을 추가 하면 이번 에는 Scoped 와 Transient 만 비교 합 니 다.
먼저 Start Up 에서 HttpContextAccessor 서 비 스 를 주입 합 니 다.그 목적 은 나중에 Scoped 에 대해 새로운 서비스 인 스 턴 스 를 얻 을 수 있 도록 하 는 것 입 니 다(두 인 스 턴 스 가 같 지만).
 services.AddHttpContextAccessor();
 /// <summary>
 ///   Transient、Scoped Guid 
 /// </summary>
 /// <returns></returns>
 List<string> GetTransientAndScopedGuidString();
public List<string> GetTransientAndScopedGuidString()
 {
 //var tempTransientService = (IOperationTransient)ServiceLocator.Instance.GetService(typeof(IOperationTransient));
 var tempTransientService = (IOperationTransient)_httpContextAccessor.HttpContext.RequestServices.GetService(typeof(IOperationTransient));
 var tempScopedService = (IOperationScoped)_httpContextAccessor.HttpContext.RequestServices.GetService(typeof(IOperationScoped));
 return new List<string>()
 {
 $"  Transient    :"+_transientOperation.GetGuid(),
 $"  Transient    :"+ tempTransientService.GetGuid(),
 $"  Scoped    :"+_scopedOperation.GetGuid(),
 $"  Scoped    :"+tempScopedService.GetGuid(),
 };
 } 
   Scoped 에 있어 서 한 번 요청 에서 같은 서 비 스 를 여러 번 방문 하 는 것 은 하나의 서비스 인 스 턴 스 를 공유 하 는 것 이 고 Transient 에 대해 서 는 매번 방문 할 때마다 새로운 서비스 인 스 턴 스 를 사용 하 는 것 을 볼 수 있 습 니 다.
이로써 이 네 가지 서비스 생명주기 에 대해 파악 한 것 은 많 지 않 은 셈 이다.
참고:
장 선생님
전원 귀뚜라미
총결산
이상 은 이 글 의 전체 내용 입 니 다.본 논문 의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 참고 학습 가치 가 있 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 댓 글 을 남 겨 주 셔 서 저희 에 대한 지지 에 감 사 드 립 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Tailwind를 ASP.NET Core 프로젝트에 통합우리는 을 사용합니다. 에서 코드를 찾을 수 있습니다. 면도기 페이지 구조를 추가합니다. "node_modules"가 설치되었습니다. "tailwind.config.js"파일이 생성되었습니다. 모든 .razor 및 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.