简体   繁体   中英

SqlDependency and asp.net mvc application not fully working

I have strange problem and question about using SqlDependency class in a normal Asp.net MVC application

I have standard controller with code:

    public ActionResult Index()
    {
        RegisterNotification();
        return View();
    }

    public void RegisterNotification()
    {
        var cs = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString;
        var sql = @"Select Data From dbo.TestTable"; 
        using (var conn = new SqlConnection(cs))
        {
            conn.Open();
            using (var cmd = new SqlCommand(sql, conn))
            {
                cmd.Notification = null;
                var sqlDependency = new SqlDependency(cmd);
                sqlDependency.OnChange += SqlDependency_OnChange;
                cmd.ExecuteNonQuery();
            }
        }

    }

    public void SqlDependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            // call some SignalR method here and re-register notification
            RegisterNotification();
        }
    }

In Global.asax is SqlDepndency initialize (on start and end methods)

Well, in first request everything working great, but after some refresh(full request) SqlDependency_OnChange calling twice and next refresh calling four times and etc.

In console application this code works fine.

Is there something wrong with my code?

(Using Sql 2012 and asp.net MVC 5.2.3 and VisualStudio IISExpress dev server)

Thanks

I think what you'll want to do is create a Singleton that will handle the SqlDependency notifications. Every time someone makes a request, a new instance of your controller is being created, which registers for new notifications. When you're getting multiple notifications, I think you'll find that it's different instances of your controller getting notified.

There's a great example of this here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM