ASP.NET Core 에서 설정 파일 을 수정 한 후 새 설정 을 자동 으로 불 러 오 는 방법 에 대한 자세 한 설명
ASP.NET Core 기본 프로그램 템 플 릿 에서 설정 파일 의 처 리 는 다음 코드 와 같 습 니 다.
config.AddJsonFile(
path: "appsettings.json",
optional: true,
reloadOnChange: true
);
config.AddJsonFile(
path: $"appsettings.{env.EnvironmentName}.json",
optional: true,
reloadOnChange: true
);
apptsettings.json 과 apptsettings.{env.Environment Name}.json 두 프로필 은 모두 선택 할 수 있 으 며 파일 이 수정 되 었 을 때 다시 불 러 올 수 있 도록 지원 합 니 다.ASP.NET Core 애플 리 케 이 션 에서 이 기능 을 이용 해 프로필 을 수정 한 후 애플 리 케 이 션 을 다시 시작 하지 않 고 수 정 된 프로필 을 자동 으로 불 러 와 시스템 정지 시간 을 줄 일 수 있 습 니 다.실현 절 차 는 다음 과 같다.
설정 API 로 주입 하기
프로그램 에 이러한 설정 형식 을 주입 한다 고 가정 합 니 다:
public class WeatherOption {
public string City { get; set; }
public int RefreshInterval { get; set; }
}
apptsettings.json 에 추 가 된 설정 은 다음 과 같 습 니 다.
{
"weather": {
"city": "GuangZhou",
"refreshInterval": 120
}
}
Startup.cs 의 Configure Services 방법 에서 설정 API 를 사용 하여 주입 합 니 다.코드 는 다음 과 같 습 니 다.
public void ConfigureServices(IServiceCollection services) {
services.Configure<WeatherOption>(Configuration.GetSection("weather"));
services.AddControllers();
}
이 단 계 는 매우 중요 합 니 다.이 설정 API 를 통 해 주입 내용 과 설정 이 있 는 노드 를 연결 할 수 있 습 니 다.밑바닥 실현 에 관심 이 있다 면 이것 을 계속 살 펴 볼 수 있다OptionsConfigurationServiceCollectionExtensions.cs이러한 방식 으로 등 록 된 내용 은 설정 파일 이 수정 되 었 을 때 자동 으로 다시 불 러 오 는 것 을 지원 합 니 다.
컨트롤 러(Controller)에 수 정 된 설정 을 불 러 옵 니 다.
컨트롤 러(Controller)가 ASP.NET Core 응용 에 의존 하 는 주입 용기 에 등 록 된 수명 주 기 는 Scoped 입 니 다.요청 할 때마다 새로운 컨트롤 러 인 스 턴 스 를 만 듭 니 다.이렇게 하면 컨트롤 러 의 구조 함수 에 IOptionsSnapshot
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase {
private WeatherOption option;
public WeatherForecastController(
IOptionsSnapshot<WeatherOption> options
) {
this.option = options.Value;
}
// GET /weatherforcase/options
[HttpGet("options")]
public ActionResult<WeatherOption> GetOption() {
return options;
}
}
물론 컨트롤 러 에서 이 IOptionsSnapshot 인터페이스 형식 을 사용 하지 않 으 려 면 Configure Services 에 WeatherOption 에 대한 주입 을 추가 할 수 있 습 니 다.코드 는 다음 과 같 습 니 다.
public void ConfigureServices(IServiceCollection services) {
services.Configure<WeatherOption>(Configuration.GetSection("weather"));
// WeatherOption , Scoped , 。
services.AddScoped(serviceProvider => {
var snapshot = serviceProvider.GetService<IOptionsSnapshot<WeatherOption>>();
return snapshot.Value;
});
services.AddControllers();
}
이렇게 하면 컨트롤 러 에 IOptionsSnapshot
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase {
private WeatherOption option;
public WeatherForecastController(
WeatherOption option
) {
this.option = option;
}
// GET /weatherforcase/options
[HttpGet("options")]
public ActionResult<WeatherOption> GetOption() {
return options;
}
}
이렇게 하면 컨트롤 러 는 코드 를 수정 하지 않 아 도 수 정 된 새 설정 을 불 러 올 수 있다.중간 부품(Middleware)에 수 정 된 설정 불 러 오기
미들웨어(Middleware)가 ASP.NET Core 응용 에 의존 하 는 주입 용기 에 등 록 된 수명 주 기 는 Singleton 입 니 다.즉,하나의 예 입 니 다.응용 이 시 작 될 때 미들웨어 에 따라 처리 연결 을 만 들 때 만 전체 인 스 턴 스 를 만 들 수 있 기 때문에 IOptionsMonitor
public class TestMiddleware {
private RequestDelegate next;
private WeatherOption option;
public TestMiddleware(
RequestDelegate next,
IOptionsMonitor<WeatherOption> monitor
) {
this.next = next;
option = monitor.CurrentValue;
// moni config change
monitor.OnChange(newValue => {
option = newValue;
});
}
public async Task Invoke(HttpContext context) {
await context.Response.WriteAsync(JsonSerializer.Serialize(option));
}
}
물론 미들웨어 의 Task Invoke(HttpContext context)방법 에서 IOptionsSnapshot
public async Task Invoke(HttpContext context) {
var snapshot = context.RequestServices.GetService<IOptionsSnapshot<WeatherOption>>();
await context.Response.WriteAsync(JsonSerializer.Serialize(snapshot.Value));
}
하지만 이렇게 하면 주입 에 의존 하 는 원칙 에서 벗 어 나 는 것 같 아 추천 하지 않 는 다.총결산
여기 서 ASP.NET Core 에서 프로필 을 수정 한 후 새 프로필 을 자동 으로 불 러 오 는 것 에 관 한 글 을 소개 합 니 다.더 많은 관련 ASP.NET Core 에서 새 프로필 을 자동 으로 불 러 옵 니 다.이전 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 도 많은 응원 부 탁 드 리 겠 습 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
작업 중 문제 해결 - (win 2003 asp. net) Session 과 페이지 전송 방법 으로 해결 방안 을 정상적으로 사용 할 수 없습니다.또한 F 는 처음에 우리 의 BP & IT 프로젝트 팀 이 Forms 폼 검증 을 사용 했다 고 판단 할 수 있 습 니 다. 페이지 를 뛰 어 넘 는 것 은http://hr.bingjun.cc/MyTask/MyTas...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.