SignalR:来自另一个项目的Access Hub类

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

我正在开发.Net Core Web应用程序,并希望在控制器类之外访问IHubContext,但我无法引用NotificationHub类。

这是我的解决方案结构,带有一些标记(红色数字):Solution structure

如果我尝试从Service项目引用NotificationHub类,它总是强调NotificationHub类,Visual Studio提供以下建议:Suggestions

NotificationHub.cs(在项目1中)

public class NotificationHub : Hub
{
    public string GetConnectionId()
    {
        return Context.ConnectionId;
    }

    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveNotification", user, message);
    }

    public Task SendPrivateMessage(string user, string message)
    {
        return Clients.User(user).SendAsync("ReceiveNotification", message);
    }
}

... Service.cs(项目2中)

private readonly IHubContext<NotificationHub> _hubContext; // it uderlines "NotificationHub"

public PDUSwitchService(ILogger<PDUSwitchService> logger, IHubContext<NotificationHub> hubContext)
{
    _logger = logger;
    _hubContext = hubContext;
}

如何从Service项目(在项目2中)访问NotificationHub类(在项目1中)?

c# asp.net visual-studio asp.net-core
1个回答
4
投票

您必须将您的集线器类移动到单独的项目,否则您将具有循环依赖项(Web项目依赖于服务和服务依赖于Web)。移动后,Web项目将引用Hub和Service项目,Service将引用Hub项目,因此问题应该得到解决。

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