重要接口或类
IHostBuilder 接口的方法
1. ConfigureAppConfiguration
IHostBuilder ConfigureAppConfiguration(Action<HostBuilderContext, IConfigurationBuilder> configureDelegate);
2.ConfigureServices
IHostBuilder ConfigureServices(Action<HostBuilderContext, IServiceCollection> configureDelegate);
3.
Host 类(Microsoft.Extensions.Hosting下)
算是只有一个方法 CreateDefaultBuilder
导入包
Microsoft.Extensions.Hosting
控制台使用泛型主机
Program.cs
public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration(builder => { builder.AddApollo(builder.Build().GetSection("apollo")).AddDefault(); }) .ConfigureServices(Services => { Services.AddHostedService<Test>(); }); }
Test.cs
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; namespace ConsoleTest { internal class Test : IHostedService { IConfiguration _configuration; public Test(IConfiguration configuration, IHostApplicationLifetime appLifetime) { _configuration = configuration; appLifetime.ApplicationStarted.Register(OnStarted); } private void OnStarted() { while (true) { Console.WriteLine(_configuration.GetValue<string>("time")); Thread.Sleep(3000); } } public Task StartAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } } }