Windows Service可以向Blazor应用发送事件通知吗?
适配你需求的实现方案
这个场景最适合用ASP.NET Core SignalR实现,它原生支持Blazor,是轻量的全双工通信方案,不需要额外引入第三方中间件,就能实现服务端主动向所有在线客户端推送消息的需求。
核心架构逻辑
- 所有DB交互逻辑保留在Windows Service侧,无需调整现有DB新增数据监测功能
- Blazor CRUD应用内置SignalR Hub作为消息转发节点,所有在线Blazor用户和Windows Service都通过长连接接入该Hub
- Windows Service监测到DB有新通知插入时,将新数据推送到SignalR Hub,由Hub同步推送给所有在线Blazor用户,无需Blazor侧单独连接DB或者轮询接口
具体实现步骤
1. Blazor CRUD应用添加SignalR Hub
首先安装SignalR依赖包:Install-Package Microsoft.AspNetCore.SignalR
新建通知Hub类:
public class NotificationHub : Hub { // 无需自定义方法,仅作为消息中转节点 }
在项目的Program.cs中注册SignalR服务并配置路由:
// 注册SignalR服务 builder.Services.AddSignalR(); // ... 其他中间件配置 // 配置Hub访问路由 app.MapHub<NotificationHub>("/notificationHub");
2. Blazor前端订阅新通知事件
在你展示通知的Blazor组件中添加SignalR客户端连接,监听推送的新通知事件,收到消息后自动刷新页面数据:
@inject NavigationManager NavigationManager @implements IAsyncDisposable private HubConnection _hubConnection; private List<Notification> _notificationList = new(); protected override async Task OnInitializedAsync() { // 初始化Hub连接 _hubConnection = new HubConnectionBuilder() .WithUrl(NavigationManager.ToAbsoluteUri("/notificationHub")) .Build(); // 监听新通知推送事件 _hubConnection.On<Notification>("ReceiveNewNotification", newNotification => { _notificationList.Insert(0, newNotification); // 触发页面刷新 StateHasChanged(); return Task.CompletedTask; }); // 启动连接 await _hubConnection.StartAsync(); } // 组件销毁时关闭连接 public async ValueTask DisposeAsync() { if (_hubConnection is not null) { await _hubConnection.DisposeAsync(); } }
3. Windows Service集成SignalR客户端推送消息
给Windows Service项目安装SignalR客户端依赖包:Install-Package Microsoft.AspNetCore.SignalR.Client
在服务启动时初始化和Blazor Hub的长连接,监测到DB有新通知时调用推送方法:
private HubConnection _hubConnection; // 服务启动时执行 protected override async void OnStart(string[] args) { _hubConnection = new HubConnectionBuilder() // 替换为你实际的Blazor应用访问地址 .WithUrl("https://你的Blazor应用部署地址/notificationHub") .Build(); // 可选:添加断连自动重连逻辑 _hubConnection.Closed += async (error) => { await Task.Delay(new Random().Next(0, 5) * 1000); await _hubConnection.StartAsync(); }; await _hubConnection.StartAsync(); } // 你现有DB新增数据监测逻辑中,检测到新通知时调用该方法推送 private async Task PushNotificationToClients(Notification newNotification) { if (_hubConnection.State == HubConnectionState.Connected) { await _hubConnection.SendAsync("ReceiveNewNotification", newNotification); } }
扩展适配方案
如果你后续有Blazor应用多实例部署的需求,只需要给SignalR配置Redis背板,即可实现跨实例的消息同步,不需要修改现有业务逻辑。
内容的提问来源于stack exchange,提问作者CuriousCarnivore
相关产品推荐
相关产品推荐

