【发布时间】: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