Hosting 主机/托管 长时间运行的服务寄宿在托管进程
托管服务==服务托管主机 任何需要在后台长期运行的服务
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace ConsoleApp1 { public class Sample01 { public class SystemClock : IHostedService { private Timer _timer; //启动服务 public Task StartAsync(CancellationToken cancellationToken) { _timer = new Timer(state => { Console.WriteLine($"Current Time:{DateTime.Now.ToLongTimeString()}"); }, null,0, 1000); return Task.CompletedTask; //返回 } //停止服务 public Task StopAsync(CancellationToken cancellationToken) { _timer?.Dispose(); return Task.CompletedTask; } } public static void Start() { var host = new HostBuilder() //宿主对象 .ConfigureServices(collection => collection //依赖注入框架 //.AddHostedService<SystemClock>() //两种方案都行 .AddSingleton<IHostedService,SystemClock>() //单例模式 ) //给容器添加服务 .Build(); //构建了宿主对象 host.Run(); //启动,寄宿在宿主的服务启动 } } }host1
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace ConsoleApp1 { public class Sample02 { /// <summary> /// 温度 /// </summary> public interface ITemperatureCollector { int Get(); } /// <summary> /// 湿度 /// </summary> public interface IHumidityCollector { int Get(); } /// <summary> /// 空气质量 /// </summary> public interface IAirQualityCollector { int Get(); } public class Collector: ITemperatureCollector, IHumidityCollector, IAirQualityCollector { int ITemperatureCollector.Get() { var random = new Random(); return random.Next(0, 100); } int IHumidityCollector.Get() { var random = new Random(); return random.Next(0, 100); } int IAirQualityCollector.Get() { var random = new Random(); return random.Next(0, 100); } } public class AirEnvironmentService : IHostedService { private readonly ITemperatureCollector _temperatureCollector; private readonly IHumidityCollector _humidityCollector; private readonly IAirQualityCollector _airQualityCollector; private Timer _timer; public AirEnvironmentService( ITemperatureCollector temperatureCollector, IHumidityCollector humidityCollector, IAirQualityCollector airQualityCollector ) { _temperatureCollector = temperatureCollector; _humidityCollector = humidityCollector; _airQualityCollector = airQualityCollector; } public Task StartAsync(CancellationToken cancellationToken) { _timer = new Timer(state => { Console.WriteLine($"温度:{_temperatureCollector.Get(), -10}" + $"湿度:{_humidityCollector.Get(), -10}" + $"空气质量:{_airQualityCollector.Get(), -10}" + $"时间:{DateTime.Now.ToLongTimeString()}"); }, null,0, 1000); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { _timer?.Dispose(); return Task.CompletedTask; } } public static void Start() { var collector = new Collector(); var host = new HostBuilder() .ConfigureServices(collection => collection .AddSingleton<ITemperatureCollector>(collector) //依赖注入 .AddSingleton<IHumidityCollector>(collector) .AddSingleton<IAirQualityCollector>(collector) .AddHostedService<AirEnvironmentService>() ).Build(); host.Run(); } } }注入
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; namespace ConsoleApp1 { public class Sample03 { /// <summary> /// 温度 /// </summary> public interface ITemperatureCollector { int Get(); } /// <summary> /// 湿度 /// </summary> public interface IHumidityCollector { int Get(); } /// <summary> /// 空气质量 /// </summary> public interface IAirQualityCollector { int Get(); } public class Collector: ITemperatureCollector, IHumidityCollector, IAirQualityCollector { int ITemperatureCollector.Get() { var random = new Random(); return random.Next(0, 100); } int IHumidityCollector.Get() { var random = new Random(); return random.Next(0, 100); } int IAirQualityCollector.Get() { var random = new Random(); return random.Next(0, 100); } } public class AirEnvironmentOptions //选项 { public long Interval { get; set; } //间隔 } public class AirEnvironmentService : IHostedService { private readonly ITemperatureCollector _temperatureCollector; private readonly IHumidityCollector _humidityCollector; private readonly IAirQualityCollector _airQualityCollector; private readonly AirEnvironmentOptions _options; private Timer _timer; public AirEnvironmentService( ITemperatureCollector temperatureCollector, IHumidityCollector humidityCollector, IAirQualityCollector airQualityCollector, IOptions<AirEnvironmentOptions> options ) { _temperatureCollector = temperatureCollector; _humidityCollector = humidityCollector; _airQualityCollector = airQualityCollector; _options = options.Value; } public Task StartAsync(CancellationToken cancellationToken) { _timer = new Timer(state => { Console.WriteLine($"温度:{_temperatureCollector.Get(), -10}" + $"湿度:{_humidityCollector.Get(), -10}" + $"空气质量:{_airQualityCollector.Get(), -10}" + $"时间:{DateTime.Now.ToLongTimeString()}"); }, null,0, _options.Interval); //通过配置文件读取的数据 return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { _timer?.Dispose(); return Task.CompletedTask; } } //appsettings.json // { // "AirEnvironment": { // "Interval": 1000 // }, // "Logging": { // "LogLevel": { // "Microsoft.*": "Warning" // } // } //} public static void Start() { var collector = new Collector(); var host = new HostBuilder() .ConfigureAppConfiguration(builder => builder.AddJsonFile("appsettings.json")) //配置托管服务的配置对象,读取配置文件 .ConfigureServices((context, collection) => collection .AddSingleton<ITemperatureCollector>(collector) .AddSingleton<IHumidityCollector>(collector) .AddSingleton<IAirQualityCollector>(collector) .AddHostedService<AirEnvironmentService>() .AddOptions() //添加选项 .Configure<AirEnvironmentOptions>( //注入选项 context.Configuration.GetSection("AirEnvironment")) //添加配置节 ).Build(); host.Run(); } //PS D:\360MoveData\Users\zzhhpe\Documents\Downloads\8、Hosting与管道\ConsoleApp1> dotnet run /enviroment=production public static void Start(string[] args) //配置环境 { var collector = new Collector(); var host = new HostBuilder() .ConfigureHostConfiguration(builder => builder.AddCommandLine(args)) //配置运行环形 .ConfigureAppConfiguration((context, builder) => builder .AddJsonFile("appsettings.json", false) //false 保证不传参数时不报错 .AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", true)) //配置托管服务的配置对象,读取配置文件 .ConfigureServices((context, collection) => collection .AddSingleton<ITemperatureCollector>(collector) //构造函数注入 .AddSingleton<IHumidityCollector>(collector) .AddSingleton<IAirQualityCollector>(collector) .AddHostedService<AirEnvironmentService>() .AddOptions() //添加选项 .Configure<AirEnvironmentOptions>( //注入选项 context.Configuration.GetSection("AirEnvironment")) //添加配置节 ).Build(); host.Run(); } } }配置
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; namespace ConsoleApp1 { public class Sample03 { /// <summary> /// 温度 /// </summary> public interface ITemperatureCollector { int Get(); } /// <summary> /// 湿度 /// </summary> public interface IHumidityCollector { int Get(); } /// <summary> /// 空气质量 /// </summary> public interface IAirQualityCollector { int Get(); } public class Collector: ITemperatureCollector, IHumidityCollector, IAirQualityCollector { int ITemperatureCollector.Get() { var random = new Random(); return random.Next(0, 100); } int IHumidityCollector.Get() { var random = new Random(); return random.Next(0, 100); } int IAirQualityCollector.Get() { var random = new Random(); return random.Next(0, 100); } } public class AirEnvironmentOptions //选项 { public long Interval { get; set; } //间隔 } public class AirEnvironmentService : IHostedService { private readonly ITemperatureCollector _temperatureCollector; private readonly IHumidityCollector _humidityCollector; private readonly IAirQualityCollector _airQualityCollector; private readonly AirEnvironmentOptions _options; private Timer _timer; public AirEnvironmentService( ITemperatureCollector temperatureCollector, IHumidityCollector humidityCollector, IAirQualityCollector airQualityCollector, IOptions<AirEnvironmentOptions> options ) { _temperatureCollector = temperatureCollector; _humidityCollector = humidityCollector; _airQualityCollector = airQualityCollector; _options = options.Value; } public Task StartAsync(CancellationToken cancellationToken) { _timer = new Timer(state => { Console.WriteLine($"温度:{_temperatureCollector.Get(), -10}" + $"湿度:{_humidityCollector.Get(), -10}" + $"空气质量:{_airQualityCollector.Get(), -10}" + $"时间:{DateTime.Now.ToLongTimeString()}"); }, null,0, _options.Interval); //通过配置文件读取的数据 return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { _timer?.Dispose(); return Task.CompletedTask; } } //appsettings.json // { // "AirEnvironment": { // "Interval": 1000 // }, // "Logging": { // "LogLevel": { // "Microsoft.*": "Warning" // } // } //} public static void Start() { var collector = new Collector(); var host = new HostBuilder() .ConfigureAppConfiguration(builder => builder.AddJsonFile("appsettings.json")) //配置托管服务的配置对象,读取配置文件 .ConfigureServices((context, collection) => collection .AddSingleton<ITemperatureCollector>(collector) .AddSingleton<IHumidityCollector>(collector) .AddSingleton<IAirQualityCollector>(collector) .AddHostedService<AirEnvironmentService>() .AddOptions() //添加选项 .Configure<AirEnvironmentOptions>( //注入选项 context.Configuration.GetSection("AirEnvironment")) //添加配置节 ).Build(); host.Run(); } //PS D:\360MoveData\Users\zzhhpe\Documents\Downloads\8、Hosting与管道\ConsoleApp1> dotnet run /enviroment=production public static void Start(string[] args) //配置环境 { var collector = new Collector(); var host = new HostBuilder() .ConfigureHostConfiguration(builder => builder.AddCommandLine(args)) //配置运行环形 .ConfigureAppConfiguration((context, builder) => builder .AddJsonFile("appsettings.json", false) //false 保证不传参数时不报错 .AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", true)) //配置托管服务的配置对象,读取配置文件 .ConfigureServices((context, collection) => collection .AddSingleton<ITemperatureCollector>(collector) //构造函数注入 .AddSingleton<IHumidityCollector>(collector) .AddSingleton<IAirQualityCollector>(collector) .AddHostedService<AirEnvironmentService>() .AddOptions() //添加选项 .Configure<AirEnvironmentOptions>( //注入选项 context.Configuration.GetSection("AirEnvironment")) //添加配置节 ).Build(); host.Run(); } } }环境参数
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.VisualBasic; namespace ConsoleApp1 { public class Sample04 { /// <summary> /// 温度 /// </summary> public interface ITemperatureCollector { int Get(); } /// <summary> /// 湿度 /// </summary> public interface IHumidityCollector { int Get(); } /// <summary> /// 空气质量 /// </summary> public interface IAirQualityCollector { int Get(); } public class Collector: ITemperatureCollector, IHumidityCollector, IAirQualityCollector { int ITemperatureCollector.Get() { var random = new Random(); return random.Next(0, 100); } int IHumidityCollector.Get() { var random = new Random(); return random.Next(0, 100); } int IAirQualityCollector.Get() { var random = new Random(); return random.Next(0, 100); } } public class AirEnvironmentOptions { public long Interval { get; set; } } public class AirEnvironmentPublisher { private const string Template = "温度:{temperature, -10}" + "湿度:{humidity, -10}" + "空气质量:{airQuality, -10}" + "时间:{now}"; private readonly Action<ILogger, int,int,int,string, Exception> _logAction; private readonly ILogger _logger; public AirEnvironmentPublisher(ILogger<AirEnvironmentPublisher> logger) { _logger = logger; _logAction = LoggerMessage.Define<int, int, int, string>(LogLevel.Information, 0, Template); } public void Publish(int temp, int humi, int airq) { _logAction(_logger, temp, humi, airq, DateTime.Now.ToLongTimeString(), null); } } public class AirEnvironmentService : IHostedService { private readonly ITemperatureCollector _temperatureCollector; private readonly IHumidityCollector _humidityCollector; private readonly IAirQualityCollector _airQualityCollector; private readonly AirEnvironmentPublisher _publisher; private readonly AirEnvironmentOptions _options; private Timer _timer; public AirEnvironmentService( ITemperatureCollector temperatureCollector, IHumidityCollector humidityCollector, IAirQualityCollector airQualityCollector, AirEnvironmentPublisher publisher, IOptions<AirEnvironmentOptions> options ) { _temperatureCollector = temperatureCollector; _humidityCollector = humidityCollector; _airQualityCollector = airQualityCollector; _publisher = publisher; _options = options.Value; } public Task StartAsync(CancellationToken cancellationToken) { _timer = new Timer(state => { _publisher.Publish( _temperatureCollector.Get(), _humidityCollector.Get(), _airQualityCollector.Get()); }, null,0, _options.Interval); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { _timer?.Dispose(); return Task.CompletedTask; } } public static void Start() { var collector = new Collector(); var host = new HostBuilder() .ConfigureAppConfiguration((context,builder) => builder.AddJsonFile("appsettings.json")) .ConfigureServices((context, collection) => collection .AddSingleton<ITemperatureCollector>(collector) .AddSingleton<IHumidityCollector>(collector) .AddSingleton<IAirQualityCollector>(collector) .AddSingleton<AirEnvironmentPublisher>() .AddHostedService<AirEnvironmentService>() .AddOptions() .Configure<AirEnvironmentOptions>( context.Configuration.GetSection("AirEnvironment")) ) .ConfigureLogging(builder => builder.AddConsole()) .Build(); host.Run(); } } }日志
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace ConsoleApp1 { public class Sample05 { public class TestService : IHostedService { private readonly IHostApplicationLifetime _lifetime; private IDisposable _tokenSource; public TestService(IHostApplicationLifetime lifetime) { _lifetime = lifetime; _lifetime.ApplicationStarted.Register(() => { Console.WriteLine($"{DateTimeOffset.Now} Application Started"); }); _lifetime.ApplicationStopping.Register(() => { Console.WriteLine($"{DateTimeOffset.Now} Application Stopping"); }); _lifetime.ApplicationStopped.Register(() => { Console.WriteLine($"{DateTimeOffset.Now} Application Stopped"); }); } public Task StartAsync(CancellationToken cancellationToken) { _tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(3)).Token.Register(_lifetime.StopApplication); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { _tokenSource?.Dispose(); return Task.CompletedTask; } } public static void Start() { var host = new HostBuilder() .ConfigureServices(collection => collection .AddHostedService<TestService>()) .Build(); host.Run(); } } }开始和停止口令
标签:Get,int,Hosting,System,管道,new,using,public From: https://www.cnblogs.com/zzhpebg/p/17588797.html