Hub.Clients.User (userId) .methodCall always returns a reference to an object that is not installed on an object instance

I have a NotificationHub class that inherits from the Hub class.

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

It always fails with

 [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 

However, if I do this:

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

It works ... What gives here? Most of the examples that I saw do not require explicitly getting the context if it is not already accessible from the Hub? I would rather not take it explicitly every time.

Here is my IoC setup:

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

Activator:

 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); } } 
+6
source share
1 answer

If you want to send something to clients from outside the hub handler methods (i.e. not while the message is being processed on the server), you should use GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();

The reason is that when a method is called to process some message on the client side, a hub instance is created using the SignalR and Clients properties. This is not the case when you call the method yourself from the server code (and, possibly, create the hub instance yourself).

The Imho error message is not very clear, and this use case should be handled better by SignalR. In any case, for the same reason, I propose to separate all methods of sending messages to clients that are designed to be called from server code to another class (not from Hub ).

+8
source

Source: https://habr.com/ru/post/989313/


All Articles