提问
如何创建 .NET Core后台服务
回答
- 引入nuget
Microsoft.Extensions.Hosting
- 创建服务
using ActiveAlarmDemo.Models;
using Microsoft.Extensions.Hosting;
namespace ActiveAlarmDemo.Services
{
public class RecordOnPlanServce : BackgroundService
{
private readonly swaggerClient _swaggerClient;
private readonly ActiveAlarmContext _activeAlarmContext;
public RecordOnPlanServce(swaggerClient swaggerClient, ActiveAlarmContext activeAlarmContext)
{
_swaggerClient = swaggerClient;
_activeAlarmContext = activeAlarmContext;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Console.WriteLine("RecordOnPlanServce");
//var c = new swaggerClient("http://172.26.176.171:18100/", new HttpClient());
var authentication = await _swaggerClient.AuthenticationAsync("client_credentials", "HLT2", "HLT2");
//var context = new ActiveAlarmContext();
for (int i = 0; i < 100; i++)
{
await Task.Delay(2000);
//var result = await c.GetAllAlarmActiveStateAsync(authentication.Access_token);
var result = await _swaggerClient.GetEquipmentActiveAlarmsAsync(authentication.Access_token, "PLSDCluster.High_Voltage.Generators.GEN4");
await _activeAlarmContext.AlarmDataValues.AddRangeAsync(result);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
var count = await _activeAlarmContext.SaveChangesAsync();
Console.WriteLine(count);
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
}
}
- 注入服务
using ActiveAlarmDemo;
using ActiveAlarmDemo.Models;
using ActiveAlarmDemo.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices((_, services) =>
services.AddTransient(typeof(swaggerClient),x=> new swaggerClient("http://****:18100/", new HttpClient()))
.AddTransient<ActiveAlarmContext>()
.AddHostedService<RecordOnPlanServce>()
.AddHostedService<RecordSubPlanService>()
.AddHostedService<ActiveAlarmService>())
.Build();
await host.RunAsync();
参考
Examples
https://gitee.com/galacode/activealarmdemo
标签:Core,activeAlarmContext,await,var,new,后台,using,NET,swaggerClient From: https://www.cnblogs.com/wuhailong/p/17008491.html