6
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.

M.skr
  • 98
  • 2
  • 9
  • Did you see: https://stackoverflow.com/questions/46904678/call-signalr-core-hub-method-from-controller/46906849#46906849 – Stephu Jun 14 '18 at 01:06

1 Answers1

12

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.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • thanks for the answer. you are right. now I inject the hubcontext in the ComputerHub constroctur. `public class ComputerHub : Hub { IHubContext _hubContext; public ComputerHub(IHubContext hubContext) { _hubcontext = hubcontext; } }` . so I can use computerhub class everywhere I inject. I hope I do not do anything wrong – M.skr Jun 14 '18 at 09:31
  • @M.skr did u find anything better, still seems odd.. i see ur comment above that should work.. but surely there a cleaner way..., seems odd that you cant inject say ComputerHub and it already know the Methods and insider call llike ur doing but... seems odd to be itself.. – Seabizkit Sep 28 '21 at 14:46
  • No, i did it that way and it worked. Frankly, I haven't had any problems. I don't know if there is a better method. – M.skr Sep 28 '21 at 19:36
  • this was exactly what I was looking for but thanks to this, now I know I am about to do it wrong. It would be nice to have a link to some other answer or maybe a short code snippet or similar but I'll still take it. Chris Pratt, Love all your movies btw. lol. – jokab Dec 22 '22 at 13:56