Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject SignalR Hub Class (not hubcontext) into Controller

public class ComputerHub : Hub
{
    private readonly DbContext _db;
    public ComputerHub(DbContext db)
    {
       _db = db;
    }

    public Task OpenLock(string connectionId)
    {
       return Clients.Client(connectionId).SendAsync("OpenLock");
    }
...
}

Startup.cs

  public void ConfigureServices(IServiceCollection services)
  {
       ...
       services.AddSignalR();
  }
  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
      ....
      app.UseSignalR(routes =>
            {
                routes.MapHub<ComputerHub>("/computerhub");
            });
      ....
  }

I want to reach the OpenLock method in a controller. How should I add to ServiceCollection the computerhub in the startup.cs.

like image 450
M.skr Avatar asked Mar 06 '23 00:03

M.skr


1 Answers

You don't seem to understand how this works. To simply answer your question, to inject the class directly, it simply needs to be registered with the service collection, like any other dependency:

services.AddScoped<ComputerHub>();

However, that's not going to do what you want it to. The class itself doesn't do anything. It's the hub context that bestows it with its powers. If you simply inject an instance of the class, without the hub context, then things like Clients (which the method you want to utilize uses) won't be set and won't have any of the functionality they need to actually do anything useful.

like image 179
Chris Pratt Avatar answered Apr 27 '23 09:04

Chris Pratt