c# - 多集线器一连,防止神级

标签 c# asp.net asp.net-core asp.net-core-signalr

来自 here ,它指出

All clients will use the same URL to establish a SignalR connection with your service ("/signalr" or your custom URL if you specified one), and that connection is used for all Hubs defined by the service.

There is no performance difference for multiple Hubs compared to defining all Hub functionality in a single class.


我想这样做的原因只是因为我唯一的集线器正在成为神级,但是,我找不到在 .NET Core 中做多个集线器的方法(同时共享一个连接)。我希望我能这样做,然后我就可以像在 Web API 中那样管理我的代码。
一种可能的解决方案可能会创建多个连接,但我必须在我的客户端管理不同的连接,只是为了防止服务器代码上的上帝类。
来自 here ,有人指出将方法映射到外部类是一种解决方法。这是唯一的解决方法吗?

最佳答案

由于 SignalR 已集成在 ASP.NET Core 中,因此无法实现 any more为多个集线器使用一个连接:

In ASP.NET Core SignalR, the connection model has been simplified. Connections are made directly to a single hub, rather than a single connection being used to share access to multiple hubs.



作为神级的解决方法,您可以使用 #region 如果您想使用单个集线器,则用于构建您的代码。

但是,我确实建议为每个目的使用不同的集线器。例如:如果我有一个聊天系统,我会使用特定的集线器 ( ChatHub ) 进行聊天。如果我也有测验系统,我会使用 QuizHub , 等等...

我真的没有看到处理多个连接的问题。因为不会有性能问题。通过为每个目的分离代码,您正在实现关注点分离(如果我错了,请纠正我)。

如果可以,只在您实际使用它的页面上初始化客户端代码(连接),方法是将 SignalR 客户端代码(每个集线器)划分到它自己的文件中。

让我们以我的最后一个示例为例:如果测验有自己的页面,则仅在该页面上加载 SignalR 客户端代码。

您可以尝试的另一件事是 AJAX 请求。有时,我将代码分离到不同的 API Controller 中,然后简单地向我的 API Controller 发出 AJAX 请求,以处理数据库事务,例如。

您还可以通过使用 IHubContext<T> 在该 Controller 中使用一些 SignalR 功能。 .

In ASP.NET Core SignalR, you can access an instance of IHubContext via dependency injection. You can inject an instance of IHubContext into a controller, middleware, or other DI service. Use the instance to send messages to clients.


class SomeController : Controller
{
    private readonly IHubContext<MyHub> _hubContext;

    public SomeController(IHubContext<MyHub> hubContext)
    {
        _hubContext = hubContext;
    }
}

using SignalR functions outside the hub 的文档,有更多的例子。

缺点是您不能使用 SignalR 的所有优秀功能,例如向组添加连接。可以在您的 Controller 中使用 。

关于c# - 多集线器一连,防止神级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53866190/

相关文章:

c# - 如何在 Java 中使用 C# System.DBNull.value?

c# - 将带有 double 的 C 结构编码到 C# - 正值错误

c# - 如何在 asp.net 中使用 png 文件中的菜单

c# - smtp.office365.com主题编码问题

ASP.NET MVC 网站部分 SSL 身份验证 cookie 未在请求中提交

json - 为什么 postman 中显示 "The field is required",即使它可以为空?

asp.net-core - 如何配置 ASP.Net TestHost 以便与 OpenId Connect 一起使用?

asp.net - 如何关闭 IIS 中的预编译?

c# - 如果使用 Autofac.Extras.Quartz,则依赖注入(inject)不起作用

c# - ASP .Net 核心日志记录 - 如何过滤记录器提供程序?