I am trying to broadcast a message to clients with a worker service in .net core 3.1. I don't have any Startup.cs (no endpoint etc.). I only have a Program.cs:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureServices((hostContext, services) =>
{
//services.AddSignalR();
services.AddHostedService<Worker>();
});
}
And this is the worker (Worker.cs):
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
//private readonly IHubContext<OperatorHub, IMessage> _operatorHub;
public Worker(ILogger<Worker> logger/*, IHubContext<OperatorHub, IMessage> operatorHub*/)
{
_logger = logger;
//_operatorHub = operatorHub;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
//await _operatorHub.Clients.All.SendMessage("hello fucking world!");
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
From what I gathered from seperate documentation (but right there is no documentation on internet about this) This is an Interface I created (IMessage.cs):
public interface IMessage
{
Task SendMessage(string message);
}
And this is a hub class (OperatorHub.cs):
public class OperatorHub : Hub<IMessage>
{
public async Task BroadcastMessage(string message)
{
await Clients.All.SendMessage(message);
}
}
When I run I get an exception because of the line services.AddSignalR(); in Program.cs.
I tried to add something like services.AddSingleton<OperatorHub>() under ConfigureServices but no luck either.
A little help would be much appreciated. Thanks in advance.