Possible to use SignalR in .net 6 service worker as a windows service?

Viewed 254

I'm new to .NET 6 and trying to convert an ASP.NET (5) background service project included SignalR to .NET 6 service worker which will be hosted as a windows service.

This is what I'm trying to do:

IHost host = Host.CreateDefaultBuilder(args)
    .UseWindowsService()
    .ConfigureServices(services =>
    {
        services.AddHttpClient();

        services.AddHostedService<PBXWorkerService>();

        services.AddSignalR();
    })
    .Build();

await host.RunAsync();

Now it needs to add SignalR endpoint such as how it added in startup class in previous version.

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapHub<AsteriskHub>("/signalr");
    });

How do I map endpoints in Program.cs class without adding startup class?

1 Answers

The correct way to achieve this in .NET 6 is create a empty project and use WebApplication in Program.cs

Example in Program.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSignalR();
builder.services.AddCors();

var app = builder.Build();
app.UseCors(options => 
                  options.AllowAnyHeader()
                  .AllowAnyMethod()
                  .AllowCredentials());

app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<MyHub>("/url");
});

app.Run();

Then you can add this logic as Worker Service in your project.

Related