2

Please tell me how I can use SignalR in not controller class. I'm using AspNetCore.SignalR 1.0.2.

For example my Hub:

public class EntryPointHub : Hub
{        
    public async Task Sended(string data)
    {
       await this.Clients.All.SendAsync("Send", data);
    }  
}

In my job class (hangfire) SignalR doesn't work, my frontend not recieved messages.

public class UpdateJob
{
    private readonly IHubContext<EntryPointHub> _hubContext;

    public UpdateJob(IHubContext<EntryPointHub> hubContext)
    {
        _hubContext = hubContext;
    }

    public void Run()
    {
        _hubContext.Clients.All.SendAsync("Send", "12321");
    }        
}

But it In my controller works well.

...
public class SimpleController: Controller
{
    private readonly IHubContext<EntryPointHub> _hubContext;        

    public SimpleController(IHubContext<EntryPointHub> hubContext)
    {
        _hubContext = hubContext;
    }

    [HttpGet("sendtoall/{message}")]
    public void SendToAll(string message)
    {
        _hubContext.Clients.All.SendAsync("Send", message);
    }        
}
IngBond
  • 601
  • 1
  • 5
  • 18
  • 1
    this is basically what you are looking for https://stackoverflow.com/questions/41829993/hangfire-dependency-injection-with-net-core. I am not sure if you can use `JobActivator` class in your case – Neville Nazerane Aug 07 '18 at 07:08

2 Answers2

2

I think you are missing .net core DI mechanism for your Job Class. In Startup.cs file add that like below:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR();
    services.AddScoped<UpdateJob>();
}
public void Configure(IApplicationBuilder app)
    {
        app.UseSignalR(routes =>
        {
            routes.MapHub<EntryPointHub>("ephub");
        });
    }

Then you need to install signalr-client for client end and calling like below in js file.

let connection = new signalR.HubConnection('/ephub');
connection.on('send', data => {
    var DisplayMessagesDiv = document.getElementById("DisplayMessages");
    DisplayMessagesDiv.innerHTML += "<br/>" + data;
});

Hope this will help you.

Humayoun_Kabir
  • 2,003
  • 1
  • 17
  • 13
0

Solved: Thank for comments, I implement JobActivator and send to activator constructor ServiceProvider like this (in Startup.Configure):

IServiceProvider serviceProvider = app.ApplicationServices.GetService<IServiceProvider>();
GlobalConfiguration.Configuration
        .UseActivator(new HangfireActivator(serviceProvider));

And add in ConfigureServices:

services.AddTransient<UpdateJob>();
IngBond
  • 601
  • 1
  • 5
  • 18