【问题标题】:Config generic hub in startup ASP.NET Core 3在启动 ASP.NET Core 3 中配置通用集线器
【发布时间】:2020-02-12 22:06:05
【问题描述】:

我有一个通用集线器:

public class SendRequestToUserSignalR<T, HubContext> where T : class where HubContext : Hub
{
    private readonly IUserConnectionManager userConnectionManager;
    private readonly IHubContext<HubContext> hubContext;

    public SendRequestToUserSignalR(IUserConnectionManager userConnectionManager , IHubContext<HubContext> hubContext)
    {
        this.userConnectionManager = userConnectionManager;
        this.hubContext = hubContext;
    }
}

而且我需要在启动时设置:

app.UseSignalR(routes =>
{
    routes.MapHub<SendRequestToUserSignalR<,>>("/sendRequest");
});

但它不起作用,我收到此错误:

使用泛型类型“SendRequestToUserSignalR”需要 2 个类型参数

我该如何解决这个问题?

【问题讨论】:

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


    【解决方案1】:

    对我来说,你的配置是完全错误的。

    您不需要将泛型类定义为集线器:

    public class SendRequestToUserSignalR : Hub
    {
        public SendRequestToUserSignalR(...services)
        {
            // code goes here...
        }
    }
    

    ConfigureServices方法中,需要启动服务:

    services.AddSignalR();
    

    Configure 方法中,您将中心映射到UseEndpoints 方法中:

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    
        endpoints.MapHub<SendRequestToUserSignalR>("/sendRequest");
    });
    

    注意: app.UseSignalR 方法在 asp.net 核心版本 3.x 中已过时

    【讨论】:

    • 这很好用,直到集线器具有依赖项,即在通过 SimpleInjector 或其他 DI 容器创建的 MyApi 上。
    猜你喜欢
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-11
    • 2017-07-10
    • 2019-06-18
    相关资源
    最近更新 更多