1

How do I send a system generated signalr message from the Azure Function itself instead of from a trigger?

The following statement, outside of a trigger, does not generate an error but it does not reach the listeners.

return new SignalRMessageAction("newMessage") {Arguments = new[] { "Sample Message" }};

With InProcess Azure SignalR Function, I could, from inside c# code, send a message by adding a new SignalRMessage to IAsyncCollector

signlRMsg = new SignalRMessage{Target = "myTarget",Arguments = new[] { "Sample Message"}};
await _signalRMessages.AddAsync(signalRMessage);//IAsyncCollector<SignalRMessage> 
PhobosFerro
  • 737
  • 6
  • 18
J Duncan
  • 11
  • 2

2 Answers2

0

Each function should have a trigger, otherwise we have no way to trigger the function. In in-process model, you can only get an IAsyncCollector<SignalRMessage> in a function with a trigger.

So, I'm not sure what you mean by "outside of a trigger". Do you mean "outside of a SignalR trigger"? If so, the answer is yes. SignalRMessageAction is the one of the return types of SignalR output binding, and you can combine it with any type of triggers. Please see an example of sending a SignalR message triggered by HTTP request.

sindo
  • 19
  • 3
0

You need to use an instance of type ServiceHubContext. That type exposes methods like .Clients.All.Send(@your message); Also you need to register the type so it becomes available throughout your application code. You can use a HostedService for that you have registered as a singleton.

 public class SignalRService : IHostedService
 {
 private const string MessageHub = "Hub";
 private readonly IConfiguration _configuration;
 private readonly ILoggerFactory _loggerFactory;

 public ServiceHubContext MessageHubContext { get; private set; }

 public SignalRService(IConfiguration configuration, ILoggerFactory loggerFactory)
 {
     _configuration = configuration;
     _loggerFactory = loggerFactory;
 }

 async Task IHostedService.StartAsync(CancellationToken cancellationToken)
 {
     using var serviceManager = new ServiceManagerBuilder()
         .WithOptions(o => o.ConnectionString = _configuration["AzureSignalRConnectionString"])
         .WithLoggerFactory(_loggerFactory)
         .BuildServiceManager();
     MessageHubContext = await serviceManager.CreateHubContextAsync(MessageHub, cancellationToken);
 } ...

Then inside program.cs register it with

s.AddSingleton<SignalRService>();
s.AddHostedService(sp => sp.GetRequiredService<SignalRService>());

Then inject SignalRService and use its 'MessageHubContext' property

hannes neukermans
  • 12,017
  • 7
  • 37
  • 56