在 .NET Core 中将 HubContext 设置为 null

Getting HubContext as null in .NET Core

我正在使用 SignalR 处理 .NET 核心应用程序。我的集线器 class 代码是:

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

我还有一个class"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 为空的异常。我该如何解决。任何帮助将不胜感激

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

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