【问题标题】:hubconnection start per every request and change contexthubconnection 根据每个请求启动并更改上下文
【发布时间】:2019-09-02 11:32:46
【问题描述】:

我需要连接到我的控制器中的 SignalR Core 集线器 (我不想使用依赖注入来调用我的集线器方法) 但我不想每次打电话给我的控制器时都启动我的HubConnection 我该怎么办?

我的控制器:

private static readonly string url = "http://localhost:10580/sgr/rtc";
public HubConnection Connection { get; private set; } = new HubConnectionBuilder().WithUrl(url).Build();

public SampleDataController()
{
    Task.Run(async () => await Connection.StartAsync());
}

[HttpGet("[action]")]
public async Task<IActionResult> GetConnectionId()
{
    try
    {
        var str = await Connection.InvokeAsync<string>("GetConnectionId");
        return Ok(str);
    }
    catch (Exception)
    {
        return BadRequest("Connection is not established");
    }
}

和我的中心:

public string GetConnectionId()
{
    return Context.ConnectionId;
}

现在我为每个请求获得不同的connectionId,但我只想为客户获得一个connectionId

【问题讨论】:

  • 您不想使用dependency injection 和`我不想每次都启动我的HubConnection`的原因是什么?您的意思是要在应用程序启动时始终创建并保持连接?一般来说,您可以为每个请求创建连接。

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


【解决方案1】:

您可以尝试将HubConnection 注册为Singleton 喜欢

public class Startup
{
    private static readonly string url = "https://localhost:44379/ChatHub";
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<HubConnection>((serviceProvider) => {
            var hubConnection = new HubConnectionBuilder().WithUrl(url).Build();
            hubConnection.StartAsync().Wait();                
            return hubConnection;
        });           
    }

}

然后用

访问HubConnection
public class HomeController : Controller
{
    private readonly HubConnection Connection;
    public HomeController(HubConnection connection)
    {
        Connection = connection;
    }

}

【讨论】:

    猜你喜欢
    • 2010-10-31
    • 2016-07-28
    • 1970-01-01
    • 2014-03-13
    • 2014-09-10
    • 2018-09-05
    • 1970-01-01
    • 2012-07-17
    • 2012-07-04
    相关资源
    最近更新 更多