发送数据我有这样一个中心:SignalR:使用GlobalHost.ConnectionManager不工作
public class MessageHubBub : Hub
{
public void ServerMethod()
{
Clients.All.sayHi("hello");
GlobalHost.ConnectionManager.GetHubContext<MessageHubBub>().Clients.All.sayHi("Hello");
}
}
我(relavent)的JavaScript看起来像这样:
$.connection.MessageHubBub.client.sayHi = function (message) {
console.log("Hello");
};
$.connection.hub.start().done(function() {
$.connection.MessageHubBub.server.ServerMethod();
});
真正奇怪的是,“你好“只打印一次,在那里我会预料它会被打印两次(因为'sayHello'被称为两次)。一般来说,我一直在使用从GlobalHost.ConnectionMananager获得的'clients'对象向客户端发送消息时遇到麻烦,所以我将这个问题提炼出来以显示哪些不起作用。
我看过很多帖子,有人在开始集线器或没有引入正确的js依赖关系时没有注册他们的js处理程序,但这些似乎不是我的问题。有什么理由不能使用GlobalHost.ConnectionManager.GetHubContext()发送消息给客户端。客户端?
编辑: 作为对Lars的回应,我确实有一个自定义的依赖关系解析器,以便我可以将Unity集成到SignalR中。我跟着一个例子,我在这里找到:http://www.kevgriffin.com/using-unity-for-dependency-injection-with-signalr/
配置的唯一行我有如下:
RouteTable.Routes.MapHubs(new HubConfiguration() { Resolver = new SignalRUnityDependencyResolver(unityContainer) });
的SignalRUnityDependencyResolver看起来是这样的:
public class SignalRUnityDependencyResolver : DefaultDependencyResolver
{
private IUnityContainer _container;
public SignalRUnityDependencyResolver(IUnityContainer container)
{
_container = container;
}
public override object GetService(Type serviceType)
{
if (_container.IsRegistered(serviceType)) return _container.Resolve(serviceType);
else return base.GetService(serviceType);
}
public override IEnumerable<object> GetServices(Type serviceType)
{
if (_container.IsRegistered(serviceType)) return _container.ResolveAll(serviceType);
else return base.GetServices(serviceType);
}
}
您是否使用了自定义的依赖解析器?你的SignalR配置代码是什么样的? –
我编辑了答案以提供一些额外的细节。 – Kyle
[SignalR +通过操作方法将消息发布到集线器]的可能重复(http://stackoverflow.com/questions/7549179/signalr-posting-a-message-to-a-hub-via-an-action -method) – Liam