Reputation: 2883
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
Upvotes: 0
Views: 2475
Reputation: 525
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
Upvotes: 1