我正在使用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的异常。我该如何解决。任何帮助将不胜感激
答案 0 :(得分:1)
如果还没有的话,可能还需要将ModuleLoader
类添加到DI容器中。您可以使用.net core
默认容器,如下所示:
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
services.AddScoped<ModuleLoader>();
}