gpt4 book ai didi

asp.net-mvc-5 - Hub.Clients.User(userId).methodCall 总是抛出未设置为对象实例的对象引用

转载 作者:行者123 更新时间:2023-12-04 11:36:31 25 4
gpt4 key购买 nike

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

最佳答案

如果您想从集线器处理程序方法之外(即不在服务器上处理消息期间)向客户端发送某些内容,则必须使用 GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
原因是当调用该方法处理某些客户端消息时,由 SignalR 和 Clients 创建集线器实例。属性已正确初始化。当您自己从服务器代码调用方法(并且可能自己创建集线器实例)时,情况并非如此。

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

关于asp.net-mvc-5 - Hub.Clients.User(userId).methodCall 总是抛出未设置为对象实例的对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30905333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com