我的MVC.Net核心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);
        }
    }
}

推荐答案

您可以使用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();
        }
    }

Reference:
Create a Client in .net
How to add client to blazor

.net相关问答推荐

Docker镜像mcr.microsoft.com/dotnet/aspnet:8.0不能在Windows上构建

使用React路由加载器获取数据不能正常工作

out 和 ref 可以用作临时变量吗?

问:在 Blazor WASM 应用程序中存储 api 密钥的最佳方式是什么?

双精度的 C++ 和 C# 十六进制值之间的差异

有什么方法可以使用 .NET 应用程序使用 git 吗?

每第 N 个字符/数字拆分一个字符串/数字?

如何在 C# 4.0 中使任务进入睡眠状态(或延迟)?

为什么需要 XmlNamespaceManager?

在 Moq Callback() 调用中设置变量值

将双精度转换为带有 N 个小数的字符串,点作为小数分隔符,并且没有千位分隔符

将 C# 编译为本机?

软件包版本始终为 1.0.0,带有 dotnet pack

如何在 C# 中将 null 值设置为 int?

Linq to SQL - 返回前 n 行

C# 中的 override 和 new 关键字有什么区别?

ConcurrentDictionary TryRemove 何时返回 false

立即检测客户端与服务器套接字的断开连接

表单不响应 KeyDown 事件

Dictionary.Add 与 Dictionary[key]=value 的区别