如何将 signalR 添加到不同项目的后台服务?

问题描述 投票:0回答:1

我的 MVC .net core 6 中有一个工作信号 R。

我的 MVC 项目中有一个后台服务,它调用我的 signalR 中心并更新我的所有页面。我已将此后台服务移至其自己的项目中,但现在无法正常工作。这可能吗?

MVC .Net Cor 6 项目:

public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

不同项目中的后台服务:

public class CalculatorConsumer : BackgroundService
{
    private readonly ILogger<CalculatorConsumer> _logger;
    private readonly ISubscriptionClient _subscriptionClient;
    private readonly IHubContext<ChatHub> _hubContext;

    public CalculatorConsumer(
        ILogger<CalculatorConsumer> logger,
        ISubscriptionClient subscriptionClient,
        IHubContext<ChatHub> hubContext)
    {
        _logger = logger;
        _subscriptionClient = subscriptionClient;
        _hubContext = hubContext;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {

        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("Worker running at: {Time}", DateTime.Now);
            await _hubContext.Clients.All.SendAsync("ReceiveMessage", $"10");
            await Task.Delay(1000, stoppingToken);
        }
    }
}
.net signalr asp.net-core-6.0 background-service
1个回答
0
投票

您可以使用

HubConnectionBuilder
创建集线器连接来调用远程集线器 URL。您不需要在单独的工作人员服务项目中注入
ChatHub
。因为你那里没有,它在服务器里。

在worker服务项目中,先安装包

Microsoft.AspNetCore.SignalR.Client
。(有时可能需要重新安装这个包)
根据您的代码,您可以修改如下

    public class CalculatorConsumer : BackgroundService
    {
        private readonly ILogger<CalculatorConsumer> _logger;


        public CalculatorConsumer(ILogger<CalculatorConsumer> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {

            var hubConnection = new HubConnectionBuilder().WithUrl("https://localhost:7218/chatHub").Build();   //change the URL to your server hub URL
            await hubConnection.StartAsync();


            hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
            {
                var encodedMsg = $"{user}: {message}";
                messages.Add(encodedMsg);
            });

            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogInformation("Worker running at: {Time}", DateTime.Now);
                await hubConnection.SendAsync("SendMessage", "workerservice", "10");
                await Task.Delay(1000, stoppingToken);         
            }
            await hubConnection.DisposeAsync();
        }
    }

参考:
在.net中创建客户端
如何将客户端添加到 blazor

© www.soinside.com 2019 - 2024. All rights reserved.