我有这样一个集线器:
public class MessageHubBub : Hub
{
public void ServerMethod()
{
Clients.All.sayHi("hello");
GlobalHost.ConnectionManager.GetHubContext<MessageHubBub>().Clients.All.sayHi( "Hello" );
}
}
Run Code Online (Sandbox Code Playgroud)
我的(相关)javascript看起来像这样:
$.connection.MessageHubBub.client.sayHi = function (message) {
console.log("Hello");
};
$.connection.hub.start().done(function () {
$.connection.MessageHubBub.server.ServerMethod();
});
Run Code Online (Sandbox Code Playgroud)
真正奇怪的是,"Hello"只打印一次,我希望它打印两次(因为'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 ) } );
Run Code Online (Sandbox Code Playgroud)
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 );
}
}
Run Code Online (Sandbox Code Playgroud)
Lar*_*ner 30
使用自定义依赖项解析程序时,仅将其传递给HubConfiguration是不够的.
您需要将解析器实例存储在某处并像这样使用它来访问连接管理器和集线器上下文:
MyDependencyResolver.Resolve<IConnectionManager>().GetHubContext<MyHub>();
Run Code Online (Sandbox Code Playgroud)
或者将GlobalHost中的默认依赖项解析器设置为您的实例:
var myResolver = new SignalRUnityDependencyResolver(unityContainer);
RouteTable.Routes.MapHubs( new HubConfiguration() { Resolver = myResolver } );
GlobalHost.DependencyResolver = myResolver;
Run Code Online (Sandbox Code Playgroud)
(然后你可以使用默认值GlobalHost.ConnectionManager.GetHubContext<MessageHubBub>())