(精华)2020年9月17日 ASP.NET Core Host主机服务详解

1.基本的使用

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
                .AddSingleton<IHostedService, SystemClock>())
                .Build();
        host.Run();
    }
}

2.依赖注入服务

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();
    }
}

3.环境变量的读取

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;
        }
    }

    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)
                .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();
    }
}

4.使用日志记录服务

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((context, builder) => builder
                .AddConfiguration(context.Configuration.GetSection("Logging"))
                .AddConsole())
            .Build();

        host.Run();
    }
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 猿与汪的秘密 设计师:上身试试 返回首页