【问题标题】:Getting HubContext as null in .NET Core在 .NET Core 中将 HubContext 设为 null
【发布时间】:2019-05-20 20:12:51
【问题描述】:

我正在使用 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 为空的异常。我该如何解决。任何帮助将不胜感激

【问题讨论】:

  • 您应该删除空的构造函数,因为这没有任何意义。这可能是你的问题。
  • 我在应用程序的某处调用 ModuleLoader 构造函数。我应该传递什么参数,我的意思是参数的值是什么。只是有点困惑。@Silvermind
  • 我的意思是如何获取 hubContext 的值
  • 那么我该如何设置@brandonhein 的值??
  • 依赖注入应该使用正确的参数调用该构造函数。也许如果您将模块加载器添加到服务并通过服务提供者手动解析模块加载器?

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-15
    • 2022-11-15
    • 1970-01-01
    • 2021-08-13
    • 2014-10-26
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    相关资源
    最近更新 更多