Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c# - Get Hub Context in SignalR Core from within another object

I am using Microsoft.AspNetCore.SignalR (latest release) and would like to get the hub context from within another object that's not a Controller. In the "full" SignalR, I could use GlobalHost.ConnectionManager.GetHubContext<MyCoolHub>();

I have seen a lot of examples of just adding Microsoft.AspNetCore.SignalR.IHubContext<MyCoolHub> as a parameter to the Ctor of a Controller, but no examples (that work) for otherwise.

ETA:

So, this is what I have working. Is this hacky?

public class MyHub : Hub
    public static IHubContext<MyHub> GlobalContext { get; private set; }
    public MyHub(IHubContext<MyHub> ctx){
        GlobalContext = ctx;
    }
}

Then I can call it as so:

await MyHub.GlobalContext.Clients.All.InvokeAsync(...)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just set IHubContext<MyHub> hubContext on calling-side constructor.

I would recommend using .net core default DI container mechanism, not creating static property.

Please refer to How do I get a reference to a Hub?

public class MyHub : Hub
{
}

public class CallingSideClass
{
    private readonly IHubContext<MyHub> _hubContext;

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

    public async Task FooMethod(...)
    {
        await _hubContext.Clients.All.InvokeAsync(...);
    }
}

public class Startup
{...
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSignalR();
        services.AddScoped<CallingSideClass>();
    }
    ... 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...