Asp.net mvc 5 methodCall始终抛出未设置为对象实例的对象引用
我有一个从Hub类继承的NotificationHub类Asp.net mvc 5 methodCall始终抛出未设置为对象实例的对象引用,asp.net-mvc-5,signalr,Asp.net Mvc 5,Signalr,我有一个从Hub类继承的NotificationHub类 public class NotificationHub : Hub { public void Send(string userId, Notification notification) { Clients.User(userId) .notificationReceived(notification); } }
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 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()代码>
原因是,当调用该方法来处理某些客户端消息时,signar会创建hub实例,并且Clients
属性已正确初始化。当您自己从服务器代码调用方法时(可能是自己创建集线器实例时),情况并非如此
Imho错误消息不是很清楚,信号员应该更好地处理这个用例。无论如何,出于同样的原因,我建议将发送消息到客户端的所有方法从服务器代码中分离到不同的类(不是从Hub
)中调用。您得到的NullReferenceException
是在调用Send()时得到的吗
来自客户端或不同服务器代码的方法?从服务器调用send时,即Clients.User(userId)。notificationReceived(notification);抛出异常
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);
}
}