控制器代码
/// <summary> /// 系统 API /// </summary> public class AppController : ControllerBase { /// <summary> /// 日志组件 /// </summary> private readonly ILogger<AppController> _logger; /// <summary> /// 后台 /// </summary> private readonly Main.IContext _app; public AppController(ILogger<AppController> logger, Main.Context app) { _logger = logger; _app = app; } [HttpGet] public IActionResult Get() { DataDll.IConsole.Context.Error(_app.Name); return new JsonResult(new { A = _app.Name }); } }
后台
public class Context : IHostedService,IContext { private readonly ILogger<Context> _logger; private readonly MqttService.IContext _mqtt = new MqttService.Context(); public Context(ILogger<Context> logger) { _logger = logger; Init(); } /// <summary> /// 初始化 /// </summary> private void Init() { _mqtt.Start(); DataDll.IConsole.Context.Success(_mqtt.Option.User); } public string Name { get { return _mqtt.Option.User; } } public Task StartAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } }
Program.cs注册依赖
//注入 后台 builder.Services.AddSingleton<Core.Jun.Next.Main.Context>(); // 独立运行后台 builder.Services.AddHostedService(service => service.GetRequiredService<Core.Jun.Next.Main.Context>());