【问题标题】:SignalR: Access Hub class from another projectSignalR:从另一个项目访问 Hub 类
【发布时间】:2018-09-17 07:49:35
【问题描述】:

我正在开发 .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;
}

我如何能够从服务项目(在项目 2 中)访问 NotificationHub 类(在项目 1 中)?

【问题讨论】:

  • 你添加了项目引用吗?
  • 我添加了从 1 到 2 的项目引用(项目 2 是支持类,它执行对数据库等的调用)。我无法添加从 2 到 1 的引用,因为它给了我一个错误:Adding this project as as reference would cause a circular dependency.

标签: c# asp.net visual-studio asp.net-core


【解决方案1】:

你必须将你的 hub 类移动到一个单独的项目中,否则你有一个循环依赖(Web 项目依赖于 Service,Service 依赖于 Web)。 移动后,Web项目会引用Hub和Service项目,Service会引用Hub项目,问题应该解决了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2013-03-28
    • 2022-12-28
    • 2015-01-26
    • 2014-03-18
    相关资源
    最近更新 更多