Host 정의
Host는 .NET app의 아래의 자원들을 캡슐화한 객체이다.
- 의존성 주입 (Dependency injection, DI)
- 로깅 (Logging)
- 설정 (Configuration)
- IHostedService 구현체들
Host 설정
host는 일반적으로 Program.cs에서 설정하고 빌드하고 실행된다.
await Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddHostedService<SampleHostedService>();
})
.Build()
.RunAsync();
기본 빌더 설정(Default builder settings)
위에부터 순서대로 적용되며 가장 최근 항목이 이전 항목을 덮어쓰기(overwrite) 한다.
- host configuration 설정:
- Environment variables prefixed with DOTNET_
- 커맨드 라인 인자 (Command-line arguments)
- app configuration 설정:
- appsettings.json
- appsettings.{envirionment}.json
- User secrets
- 환경 변수(Envirionment variables)
- 커맨드 라인 인자 (Command-line arguments)
ASP.NET Core Web Host
Learn about Web Host in ASP.NET Core, which is responsible for app startup and lifetime management.
learn.microsoft.com
예제 코드
class Program
{
static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
private static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureHostConfiguration(configHost =>
{
configHost.SetBasePath(Directory.GetCurrentDirectory());
configHost.AddJsonFile("hostsettings.json", optional: true);
configHost.AddEnvironmentVariables(prefix: "MYDEMOAPP_");
configHost.AddCommandLine(args);
})
.ConfigureAppConfiguration(app =>
{
app.AddJsonFile("appsettings.json"); ;
});
}
}
실제 예시 : 도커 컨테이너로 app 실행 시 커맨드 라인으로 환경변수 전달
command-line으로 입력하기 때문에 우선순위가 높아서 다른 설정을 덮어쓰기 하면서 적용된다.
환경변수 전달 시 : 를 __로 변경해서 전달하자
Notice the __ in the environment variable — that’s a platform — safe way to indicate nested configuration i.e. that gets loaded in config as ConnectionStrings:MyConnection
ConnectionStrings:MyConnection=myDevDataSource >> ConnectionStrings__MyConnection=myDevDataSource
함께 읽으면 좋은 글
The confusion of ASP.NET Configuration with environment variables
What comes after what in config?
gparlakov.medium.com
appSettings.json for .NET Core app in Docker?
I am running a .net core app in a docker container. Here is my docker file (just to build a dev environment): FROM microsoft/dotnet:1.0.1-sdk-projectjson ENV ASPNET_ENV Development COPY bin/Debug/
stackoverflow.com
Docker, .net core and environment variables.
We are going to work with environment variables in our service. With Docker to run the service and we will use an extension to see it.
medium.com
참고 사이트
.NET Generic Host in ASP.NET Core
Use .NET Core Generic Host in ASP.NET Core apps. Generic Host is responsible for app startup and lifetime management.
learn.microsoft.com
The Code Blogger - .NET Generic Host – Host Configuration vs App Configuration
explains the similarities and differences between host configurations and app configurations in .NET applications
thecodeblogger.com
'프로그래밍 > C#' 카테고리의 다른 글
C# 간단하게 10진수를 2진수, 16진수로 변환하기 (0) | 2024.05.22 |
---|---|
C# PadLeft, PadRight에 대해서 (1) | 2024.05.08 |
C# 비동기 프로그래밍으로 반응성 개선하기 (0) | 2024.04.11 |
C# 모나드 설계 패턴 소개 (1) | 2024.04.09 |
.NET Options Pattern 사용하기 (0) | 2024.04.09 |
댓글