İbrahim Akgün
İbrahim Akgün

Reputation: 1567

Get Instance of HubContext for re-use anywhere At SelfHosted Asp.net core Application

I have got a self hosted asp.net core app working at console. I can send message from my c# windows forms clients. But i want to send message anywhere in my server class to clients. Not one time message. So I need hubcontext instance for re-use it.

I have used IHubContext implement but im getting NullReference exception when I use hub context.

This is my Hub.

 public class UniveraHub : Microsoft.AspNetCore.SignalR.Hub
{
    public string GetConnectionId()
    {
        return Context.ConnectionId;
    }

    public async Task SendMessage(string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", message);
    }

}

This is my Startup Class

   public class Startup
{

    public void Configure(IApplicationBuilder app)
    {

        app.UseSignalR(routes =>
        {
            routes.MapHub<UniveraHub>("/UniveraHub");
        });


    }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSignalR();
        services.AddScoped<MyHubHelper>();
    }
}

This is my HubHelper Class

 public class MyHubHelper 
{
    private readonly IHubContext<UniveraHub> _hubContext;

    public MyHubHelper(IHubContext<UniveraHub> hubContext)
    {
        _hubContext = hubContext;
    }

    public MyHubHelper()
    {

    }

    public void SendOutAlert(string msg)
    {
        _hubContext.Clients.All.SendAsync("ReceivedMessage", msg);
    }
}

This program.cs that I'm using my helper class for send message to clients

  MyHubHelper helper = new MyHubHelper();
  helper.SendOutAlert("Hi from server!");

Upvotes: 0

Views: 752

Answers (1)

Ali
Ali

Reputation: 1085

In Program.cs you can use like below:

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args)
                    .Build();

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            var helper = services.GetRequiredService<MyHubHelper>();
            helper.SendOutAlert("Hi from server!");
        }

        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

Upvotes: 1

Related Questions