Search code examples
c#.net-coresignalrsignalr-hub

Getting HubContext as null in .NET Core


I am working with .NET core application using SignalR. My hub class code is:

public class LiveDataHub : Hub
{
    public async Task GetUpdatedDataFromServer()
    {
        try
        {
            var dal = new DAL();
            var dashboardVM = dal.GetDashboardViewModels();

            Clients.Caller.SendAsync("UpdatePortalWithUpdatedData", dashboardVM);
        }
        catch(Exception ex)
        {

        }
    }
}

My Startup.cs code is:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseSignalR(routes =>
        {
            routes.MapHub<LiveDataHub>("/LiveDataHub");
        });
}

I have another class "ModuleLoader", whose code is:

public class ModuleLoader
{
    GlobalCache _globalCache = GlobalCache.GetInstance();
    private readonly IHubContext<LiveDataHub> _hubContext;
    public ModuleLoader()
    {

    }

    public ModuleLoader(IHubContext<LiveDataHub> hubContext)
    {
        _hubContext = hubContext;
    }

    private void OnAdapterGroupDataReceived(DeviceAdapterGroup deviceAdapterGroup)
    {
        var dal = new DAL();
        dal.InsertOrUpdateAllAdapters(deviceAdapterGroup.AdapterGroup);

        if(deviceAdapterGroup != null)
        {
            dal.InsertAllDeviceAdapter(deviceAdapterGroup);
        }

        var allAdapters = dal.GetAllAdaptersConnectedToDevice(deviceAdapterGroup.DeviceId);
        var adaptersToDelete = allAdapters.Except(deviceAdapterGroup.AdapterGroup.Select(x => x.AdapterId)).ToList();
        if (adaptersToDelete != null && adaptersToDelete.Count > 0)
            dal.DeleteAllAdapters(adaptersToDelete);

        var dashboardVM = dal.GetDashboardViewModels();

        _hubContext.Clients.All.SendAsync("UpdatePortalWithUpdatedData", dashboardVM);

    }
}

Issue is that when i run this code, i get the exception that _hubContext is null. How can i resolve it. Any help would be much appreciated


Solution

  • You might also need to add your ModuleLoader class into a DI container if you haven't already. You can use the .net core default container as shown below:

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