我使用的是SignalR 2.2.1,这是NuGet的最新版本。我反对使用dynamic
,因此总是首选强类型。
我的项目有两个“客户类”,因此有两个中心:
ChatClient
+ ChatHub : Hub<IChatClient>
,它们是交换聊天应用程序消息的客户端。AdminClient
+ AdminHub : Hub<IAdminClient>
,具有特殊管理权限的客户在AdminHub
我希望调用ChatHub
的方法,例如从数据库加载邮件并将其广播到ChatHub
的所有用户:
这是我的逻辑(缩写):
public interface IChatClient {
void ReceiveMessage(String message);
}
public class AdminHub : Hub<IAdminClient> {
// this method is called from the Admin client
public void ShowMotdToRandomUser() {
String message = GetMessageOfTheDayFromDatabase( ... );
// get the Chat hub:
DefaultHubManager defaultHubs = new DefaultHubManager( GlobalHost.DependencyResolver );
ChatHub chatHub = defaultHubs.ResolveHub( "Chat" ) as ChatHub;
chatHub.Context = this.Context; // because chatHub.Context == null
chatHub.InternalSendMessageToRandomUser( message );
}
}
public class ChatHub : Hub<IChatClient> {
// this is a normal hub method that chat hub clients call
public void SendMessage(String message) {
this.Clients.All.ReceiveMessage( message );
}
// this is the special method called from AdminHub:
internal void InternalSendMessageToRandomUser(String message) {
String connectionId = GetRandomConnectionId( ... ); // the Hub stores all connectionIds from OnConnected to static state
this.Client( connectionId ).ReceiveMessage( message );
}
}
然而,在IChatClient.ReceiveMessage
:
NullReferenceException {"Object reference not set to an instance of an object."}
at Microsoft.AspNet.SignalR.Hubs.SignalProxy.Invoke(String method, Object[] args)
at Microsoft.AspNet.SignalR.Hubs.TypedClientBuilder.IChatHubClientImpl.ReceiveMessage(String )
at MyProject.ChatHub.InternalSendMessageToRandomUser(String message)
at MyProject.AdminHub.ShowMotdToRandomUser(String message)
at lambda_method(Closure , IHub , Object[] )
at Microsoft.AspNet.SignalR.Hubs.HubMethodDispatcher.<>c__DisplayClass10_0.<WrapVoidAction>b__0(IHub hub, Object[] parameters)
at Microsoft.AspNet.SignalR.Hubs.HubMethodDispatcher.Execute(IHub hub, Object[] parameters)
at Microsoft.AspNet.SignalR.Hubs.HubDispatcher.Incoming(IHubIncomingInvokerContext context)