在.NET Core中将HubContext获取为null

时间:2019-05-20 07:49:38

标签: c# .net-core signalr signalr-hub

我正在使用SignalR处理.NET核心应用程序。我的中心类代码是:

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)
        {

        }
    }
}

我的Startup.cs代码是:

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

我还有另一个类“ ModuleLoader”,其代码是:

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);

    }
}

问题是,当我运行此代码时,我得到了_hubContext为null的异常。我该如何解决。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

如果还没有的话,可能还需要将ModuleLoader类添加到DI容器中。您可以使用.net core默认容器,如下所示:

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