简体   繁体   English

SqlDependency和ASP.NET MVC应用程序无法完全正常运行

[英]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 我在普通的Asp.net MVC应用程序中使用SqlDependency类时遇到奇怪的问题和疑问

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) Global.asaxSqlDepndency初始化(关于start和end方法)

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. 好吧,在第一个请求中,一切工作都很好,但是在进行几次刷新(完全请求)之后, SqlDependency_OnChange调用了两次,而下一次刷新调用了四次, SqlDependency_OnChange

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) (使用Sql 2012和ASP.NET MVC 5.2.3和VisualStudio IISExpress开发服务器)

Thanks 谢谢

I think what you'll want to do is create a Singleton that will handle the SqlDependency notifications. 我认为您想要做的是创建一个处理SqlDependency通知的Singleton。 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 有这样一个很好的例子在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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