0
votes

I am able to send the message from SignalR hub from within the Hub but not from outside the hub. The following code does not work:

public class MessageSender
{
    private readonly ILogger<MessageSender> _logger;
    private readonly IHubContext<MessageHub> _context;

    public MessageSender(ILogger<MessageSender> logger, IHubContext<MessageHub> context)
    {
        _logger = logger;
        _context = context;
    }

    public async Task SendTestMessage()
    {
         Console.WriteLine("Sending Test Message to Client");
         await _context.Clients.All.SendAsync("TestMessageReceived", new SampleData());
    }
}

However the following code works:

public class MessageHub : Hub
{ 
    public async Task InitiateConnection(SampleData data)
    {
        Console.WriteLine($"{data.Text});
        await Clients.All.SendAsync("TestMessageReceived", new SampleData());
    }
}

My client application (C#) is able to communicate to the server and call "InitiateConnection" method in hub which in return calls the "TestMessageReceived" method of the client which works fine.

Why is the MessageSender not able to send the messages ? Probably I am missing something very small. I am using .Net Core and both Server and Client are on .Net 5

1

1 Answers

0
votes

I have solved this problem, for anyone encountering the same issue, here is what was wrong in my case.

I was hosting SignalR on a kestrel server running in Windows Service, but I created two dependency injection containers, one for Windows Service to do this services.AddHostedService<Worker>(); And another to run web server on kestrel and host SignalR like this

webHostBuilder.Configure((context, app) =>
{
    app.UseRouting();
    app.UseCors();
    app.UseMvc();
    app.UseEndpoints(endpoints => { endpoints.MapHub<MessageHub>("/myendpoint"); });
});

So my MessageSender class which was being used by a task running in Windows Service did not have any connections in the _context.Clients.All

There is supposed to be only one CreateDefaultBuilder https://github.com/aspnet/SignalR/issues/2347