从SignalR中的客户端调用Hub类之外的服务器方法

时间:2014-07-21 19:57:59

标签: c# asp.net-mvc signalr taskfactory

考虑下面的课程:

using Microsoft.AspNet.SignalR;
public class TwitterStream
    {
        // Hub Context
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<GeoFeedHub>();

        public void ChangeStreamBounds(double latitude, double longitude)
        {
            Debug.WriteLine(latitude + "-" + longitude);
        }

        // Lots of other interesting code redacted
   }

是否可以从客户端调用ChangeStreamBounds方法,即使它在Hub类之外?可以从服务器(以及Hub类外部)调用客户端函数,但是可以反过来这样做吗?

不幸的是,我已经支持自己进入一个角落,代码必须从我编写的类中执行(而不是来自Hub本身 - 除非您当然可以运行SignalR Hub作为任务工厂)

1 个答案:

答案 0 :(得分:2)

您的问题的答案可能涉及HubConnectionIHubProxy(允许您绑定到中心方法调用)或较低级别的API,但我认为您可能会去这是错误的方式。

从概念上讲,您希望GeoFeedHub处理客户端请求,并希望TwitterStream类处理与Twitter API的交互。因此,您的GeoFeedHub类依赖TwitterStream

您的TwitterStream班级有async个方法,这是fully supported in SignalR。您可以使用调用TwitterStream的异步Hub方法,从而无需在TaskFactory中使用Global.asax

而不是在应用程序启动时创建TwitterStream并尝试找到一种方法将Hub调用绑定到它(向后依赖并违反单一责任原则),让Hub成为一个更清洁的方式您的实时客户端之间的联系点,并将TwitterStream的实例注入GeoFeedHub,以便Hub可以访问Twitter API。


这里有一些示例代码可以说明这个想法:

public class GeoFeedHub : Hub
{
    // Declare dependency on TwitterStream class
    private readonly TwitterStream _twitterStream;

    // Use constructor injection to get an instance of TwitterStream
    public GeoFeedHub(TwitterStream _twitterStream)
    {
        _twitterStream = _twitterStream;
    }

    // Clients can call this method, which uses the instance of TwitterStream
    public async Task SetStreamBounds(double latitude, double longitude)
    {
        await _twitterStream.SetStreamBoundsAsync(latitude, longitude);
    }
}


public class TwitterStream
{
    public TwitterStream() 
    {
    }

    public async Task SetStreamBoundsAsync(double latitude, double longitude)
    {
        // Do something with Twitter here maybe?
        await SomeComponent.SetStreamBoundsAsync(latitude, longitude);
    }

    // More awesome code here
}

我在示例中使用了DI,所以这里有一些粘合代码,你需要将它连接起来。此代码将进入您的App_Start文件夹:

// Configure Unity as our DI container
public class UnityConfig
{

    private static readonly Lazy<IUnityContainer> Container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    });

    public static IUnityContainer GetConfiguredContainer()
    {
        return Container.Value;
    }


    private static void RegisterTypes(IUnityContainer container)
    {
        var twitterService = new TwitterService();
        container.RegisterInstance(twitterService);

        /*
         * Using RegisterInstance effectively makes a Singleton instance of 
         * the object accessible throughout the application.  If you don't need 
         * (or want) the class to be shared among all clients, then use 
         * container.RegisterType<TwitterService, TwitterService>();
         * which will create a new instance for each client (i.e. each time a Hub
         * is created, you'll get a brand new TwitterService object)
         */
    }
}


// If you're using ASP.NET, this can be used to set the DependencyResolver for SignalR 
// so it uses your configured container

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(UnitySignalRActivator), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(UnitySignalRActivator), "Shutdown")]

public static class UnitySignalRActivator
{
    public static void Start() 
    {
        var container = UnityConfig.GetConfiguredContainer();
        GlobalHost.DependencyResolver = new SignalRUnityDependencyResolver(container);
    }

    public static void Shutdown()
    {
        var container = UnityConfig.GetConfiguredContainer();
        container.Dispose();
    }
}

public class SignalRUnityDependencyResolver : DefaultDependencyResolver
{
    private readonly IUnityContainer _container;

    public SignalRUnityDependencyResolver(IUnityContainer container)
    {
        _container = container;
    }

    public override object GetService(Type serviceType)
    {
        return _container.IsRegistered(serviceType) 
            ? _container.Resolve(serviceType) 
            : base.GetService(serviceType);
    }

    public override IEnumerable<object> GetServices(Type serviceType)
    {
        return _container.IsRegistered(serviceType) 
            ? _container.ResolveAll(serviceType) 
            : base.GetServices(serviceType);
    }
}