【问题标题】:Hub.Clients.User(userId).methodCall always throws Object reference not set to an instance of an objectHub.Clients.User(userId).methodCall 总是抛出未设置为对象实例的对象引用
【发布时间】:2015-07-09 18:45:13
【问题描述】:

我有一个继承自 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);
        }
    }

【问题讨论】:

  • 你得到的NullReferenceException,是从客户端调用Send()方法还是从不同的服务器代码?
  • 是从服务器调用发送时,Clients.User(userId) .notificationReceived(notification);抛出异常

标签: asp.net-mvc-5 signalr


【解决方案1】:

如果您想从集线器处理程序方法之外(即不在服务器上处理消息期间)向客户端发送内容,您必须使用GlobalHost.ConnectionManager.GetHubContext&lt;NotificationHub&gt;();

原因是当调用该方法来处理一些客户端消息时,由 SignalR 创建集线器实例并且正确初始化了Clients 属性。当您从服务器代码中自己调用方法(并且可能自己创建集线器实例)时,情况并非如此。

恕我直言,错误消息不是很清楚,这个用例应该由 SignalR 更好地处理。无论如何,出于同样的原因,我建议将所有向客户端发送消息的方法分开,这些方法旨在从服务器代码调用到不同的类(不是从 Hub 派生的)。

【讨论】:

    猜你喜欢
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 2013-11-17
    相关资源
    最近更新 更多