Search code examples
javascriptasp.net-mvc-3signalrsqldependency

Using SignalR with SqlDependency to push database updates


Is is possible to use SignalR in combination with SqlCacheDependency (or SqlDependency) to push database updates directly to the browser ? Maybe there is an other way to achieve this functionality ?

The only thing i can get working now includes having to call addMessage from the async call that does an update to the datase, but that doesn't really cover updates from different sources ( for example a background service that updates the table ).


Solution

  • Ok, i figured it out, or at least, one way to do it.

    What i failed to understand initially is that you need to use that code from within an mvc controller, once you've done that, you can, obviously, call that controller from any other location or application as well, using the WebRequest class.

    @Hightechrider For the sake off completeness, you need to include 2 more references to make that piece of code work. This demo code is done with a PersistentConnection, but the principle for the hub is the same off course.

    EDIT: I'm now using a thread inside my asp.net mvc to manage the sqldependency, this feels like a more integrated solution. Check this post on how to implement background processing in asp.net "the right way" http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;    
    
    using SignalR.Infrastructure;
    using SignalR.Hosting.AspNet;
    using SignalR;
    
    namespace SignalRDemo.Controllers
    {
        public class DemoController : Controller
        {
            public void sendMessage( string message)
            {
                IConnectionManager connectionManager = AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
                IConnection connection = connectionManager.GetConnection<MyConnection>();
    
                connection.Broadcast(message);
            }
        }
    }