从 .net Core 中的外部类访问 SignalR Hub 实例

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

我想从另一个类访问我的queueHub。到目前为止,我有以下代码,但在运行代码时出现此错误。

System.AggregateException:“无法构造某些服务(验证服务描述符时出错”ServiceType:BackEnd.Model.ServerLogger Lifetime:Singleton ImplementType:BackEnd.Model.ServerLogger”:无法解析类型“Microsoft.尝试激活“BackEnd.Model.ServerLogger”时出现 AspNet.SignalR.IHubContext`1[BackEnd.Hubs.QueueHub]'。)'

这是我的中心:

using BackEnd.Model;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace BackEnd.Hubs
{
    public class QueueHub : Hub
    {

        public async Task JoinQueue(string userToken)
        {
            QueueItem user = new QueueItem
            {
                UserToken = userToken,
                ConnectionString = Context.ConnectionId
            };

            GlobalQueueManager.Enqueue(user);

        }

        public async Task notifyUser(QueueItem user, string matchId)
        {
            await Clients.Client(user.ConnectionString).SendAsync("notifyMatchStart", matchId);
        }

        public override Task OnConnectedAsync()
        {
            string connectionId = Context.ConnectionId;
            Console.WriteLine($"{connectionId} is Connected to the server");
            return base.OnConnectedAsync();
        }

    }
}

这是我的课:

using BackEnd.Hubs;
using Microsoft.AspNet.SignalR;

namespace BackEnd.Model
{
    public class ServerLogger
    {
        private readonly IHubContext<QueueHub> _queueHub;
        private readonly Timer _timer;

        public ServerLogger(IHubContext<QueueHub> queueHub)
        {
            _timer = new Timer(LogQueueCount, null, TimeSpan.Zero, TimeSpan.FromSeconds(10));
            _queueHub = queueHub;
        }

        private async void LogQueueCount(object state)
        {
            var queueCount = GlobalQueueManager.GetQueueCount();
            Console.WriteLine($"Queue Count: {queueCount}");

            if(queueCount >= 2)
            {
                List<QueueItem> matchingUsers = new List<QueueItem>();
                for(int i = 0; i< 2; i++)
                {
                    QueueItem player = GlobalQueueManager.Dequeue();
                    matchingUsers.Add(player);
                }
                foreach(QueueItem item in matchingUsers)
                {
                   await _queueHub.Clients.Client(item.ConnectionString).notifyUser(item, "tesSTR");

                }

            }
        }

    }
}
c# .net asp.net-core dependency-injection asp.net-core-signalr
1个回答
0
投票

你应该使用

using Microsoft.AspNetCore.SignalR;

在你的

ServerLogger.cs file


我已经使用

using Microsoft.AspNet.SignalR;
重现了该问题,并面临同样的问题。

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