主机 Host
一、泛型主机
泛型主机主要基于 HostBuilder 类
- 对于普通的泛型主机,它的实现方式是:
class Program
{
static async Task Main(string[] args)
{
await CreateHostBuilder(args).Build().RunAsync();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
// .ConfigureHostConfiguration(configHost =>
// {
// configHost.SetBasePath(Directory.GetCurrentDirectory());
// configHost.AddJsonFile("hostsettings.json", optional: true);
// configHost.AddEnvironmentVariables(prefix: "DOTNET_");
// configHost.AddCommandLine(args);
// })
// 配置各种配置
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddEnvironmentVariables(prefix: "DOTNET_");
config.AddJsonFile("hostsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"hostsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddCommandLine(args);
})
// 直接配置环境变量
//.UseEnvironment("Development")
// 配置注册服务
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<LifetimeEventsHostedService>();
})
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
});
}
- 对于LifetimeEventsHostedService类:
internal class LifetimeEventsHostedService : IHostedService
{
private readonly ILogger _logger;
private readonly IHostApplicationLifetime _appLifetime;
private readonly IConfiguration _config;
public LifetimeEventsHostedService(
ILogger<LifetimeEventsHostedService> logger,
IHostApplicationLifetime appLifetime, IConfiguration config)
{
_logger = logger;
_appLifetime = appLifetime;
_config = config;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_appLifetime.ApplicationStarted.Register(OnStarted);
_appLifetime.ApplicationStopping.Register(OnStopping);
_appLifetime.ApplicationStopped.Register(OnStopped);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
private void OnStarted()
{
_logger.LogInformation("OnStarted has been called.");
var appName = _config.GetValue<string>("AppName");
_logger.LogInformation($"Current AppName Environment:{appName}");
// Perform post-startup activities here
}
private void OnStopping()
{
_logger.LogInformation("OnStopping has been called.");
// Perform on-stopping activities here
}
private void OnStopped()
{
_logger.LogInformation("OnStopped has been called.");
// Perform post-stopped activities here
}
}
- 应用不同的配置:我们一般使用环境变量来区分
hostsettings.json
hostsettings.{Environment}.json
网友评论