Asp.net-Mvc-5

Hub.Clients.User(userId).methodCall 總是拋出未設置為對象實例的對象引用

  • July 9, 2015

我有一個繼承自 Hub 類的 NotificationHub 類。

public class NotificationHub : Hub
   {
       public void Send(string userId, Notification notification)
       {
           Clients.User(userId)
               .notificationReceived(notification);
       }
   }

這總是失敗

[NullReferenceException: Object reference not set to an instance of an object.]
  Microsoft.AspNet.SignalR.Hubs.SignalProxy.Invoke(String method, Object[] args) +88
  Microsoft.AspNet.SignalR.Hubs.SignalProxy.TryInvokeMember(InvokeMemberBinder binder, Object[] args, Object& result) +12
  CallSite.Target(Closure , CallSite , Object , <>f__AnonymousType0`4 ) +351

但是,如果我這樣做:

public class NotificationHub : Hub
   {
       public void Send(string userId, Notification notification)
       {
           var context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();

           context.Clients.User(userId)
               .notificationReceived(notification);
       }
   }

它有效….這裡給出了什麼?我見過的大多數範例都不需要顯式獲取上下文,是否應該還不能從 Hub 獲得?我寧願不必每次都明確地抓住它。

這是我的 IoC 設置:

GlobalHost.DependencyResolver.Register(typeof(IHubActivator), () => new SimpleInjectorHubActivator(container));
GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => new SignalRHubUserIdProvider());

活化劑:

public class SimpleInjectorHubActivator : IHubActivator
   {
       private readonly Container _container;

       public SimpleInjectorHubActivator(Container container)
       {
           _container = container;
       }

       public IHub Create(HubDescriptor descriptor)
       {
           return (IHub) _container.GetInstance(descriptor.HubType);
       }
   }

如果您想從集線器處理程序方法之外(即不在伺服器上處理消息期間)向客戶端發送某些內容,則必須使用GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();

原因是當呼叫該方法處理某些客戶端消息時,SignalR 創建集線器實例並且Clients正確初始化屬性。當您自己從伺服器程式碼呼叫方法(並且可能自己創建集線器實例)時,情況並非如此。

恕我直言錯誤消息不是很清楚,這個案例應該由 SignalR 更好地處理。無論如何,出於同樣的原因,我建議將所有向客戶端發送消息的方法分開,這些方法旨在從伺服器程式碼呼叫到不同的類(不是從Hub.

引用自:https://stackoverflow.com/questions/30905333