asp.net core 3.1 - Worker Service Template - SignalR Implementation

Viewed 309

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.

1 Answers

It seems like the base template does not include the library/package that you want to use for signalr, nuget (.net pacakage manager) will have to but used to add it. Try adding the Microsoft.AspNetCore.SignalR nuget package or edit your .csproj file to add the package manually to look similar to this:

<Project Sdk="Microsoft.NET.Sdk.Worker">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.4"/>
    <PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.1.0"/>
  </ItemGroup>
</Project>
Related