I'm looking into starting a long running task when SignalR starts and then sending data from it to the client.
From what I could find the place to run code on startup is inside Startup.Configure(IApplicationBuilder app, IHostingEnvironment env)
method.
When using ASP.NET SignalR
I can then send messages to frontend using:
var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
context.Clients.All.Send("Admin", "message");
In ASP.NET Core SignalR
the same is achieved by injecting an IHubContext
see . But I can't use that in the Configure
method since it is not possible to inject anything into it.
Where can I inject IHubContext
in a method which is called when SignalR starts so I can start the long running task?
I think the best approach is using a hosted-service . You could do something like this:
internal class MySignalRService : IHostedService, IDisposable
{
private readonly IHubContext _hubContext;
public MySignalRService(IHubContext hubContext)
{
_hubContext = hubContext;
}
public Task StartAsync(CancellationToken cancellationToken)
{
//Setup some scheduler to do your job
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
}
public void Dispose()
{
}
}
And then
services.AddHostedService<MySignalRService>();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.