无法使用SqlDependency接收更改通知

时间:2017-07-30 09:17:44

标签: c# service-broker sqldependency

我第一次使用Sql Server Service Broker,尝试在特定表中发生更改时订阅通知。当我致电command.ExecuteReader()时,我收到以下异常:

  

System.InvalidOperationException:在不提供选项值的情况下使用SqlDependency时,必须在执行添加到SqlDependency实例的命令之前调用SqlDependency.Start()。

我已经创建了一个重现场景的测试(省略了一些相关的简洁方法),如下所示:

private string _queueName = "EventsToPublishChangeMessages";
    private bool _notificationReceived;

    [Test]
    public void WhyDoesExceptionIndcateSqlDependencyStartHasNotBeenCalledPriorToCommandExecuteReader()
    {
        Console.WriteLine($"canRequestNotifications: {CanRequestNotifications()}"); // returns true
        var connectionString = GetConnectionString();
        var started = SqlDependency.Start(connectionString, _queueName); // exception below seems to suggest that I haven't started the SqlDependency. Am I doing something wrong on this line?
        Console.WriteLine($"Started:{started}"); // returns true
        var connection = new SqlConnection(connectionString);
        var command = new SqlCommand("SELECT Id, EventType, [Data], Created FROM dbo.EventsToPublish", connection);
        var sqlDependency = new SqlDependency(command);
        sqlDependency.OnChange += OnChange;
        connection.Open();

        // The following line causes the exception:
        // System.InvalidOperationException : When using SqlDependency without providing an options value, SqlDependency.Start() must be called prior to execution of a command added to the SqlDependency instance.
        // But you can see that I *did* call SqlDependency.Start() above.
        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                Process(reader);
            }
        }

        TryToTriggerANotification(connectionString);
        Thread.Sleep(5000); // ie. wait a few seconds to ensure notification-handling background thread has had a chance to complete.

        Assert.That(_notificationReceived, Is.True);
    }

    private void TryToTriggerANotification(string connectionString)
    {
        using (var connection = new SqlConnection(connectionString))
        {
            using (var command = new SqlCommand(
                    "INSERT INTO dbo.EventsToPublish(Id, EventType, [Data], Created) VALUES(newid(), 'StackOverflowQuestionTest', '', GETDATE())",
                    connection))
            {
                connection.Open();
                command.ExecuteNonQuery();
            }
        }
    }

    private void OnChange(object sender, SqlNotificationEventArgs e)
    {
        _notificationReceived = true;
    }

    private bool CanRequestNotifications()
    {
        try
        {
            var sqlClientPermission = new SqlClientPermission(PermissionState.Unrestricted);
            sqlClientPermission.Demand();
            return true;
        }
        catch
        {
            return false;
        }
    }

我发布了以下SQL查询,试图更好地了解正在发生的事情:

select * from sys.service_queues -- can see my EventsToPublishChangeMessages queue
select is_broker_enabled from sys.databases where database_id=db_id() -- returns 1
select * from sys.dm_qn_subscriptions -- returns nothing
select * from sys.transmission_queue -- returns nothing

有没有人对我可能做错了什么有任何想法?

1 个答案:

答案 0 :(得分:0)

错误消息显示:

  在执行添加到SqlDependency实例的命令之前必须调用

SqlDependency.Start()

SqlDependency.Start州的帮助:

  

启动侦听器以接收依赖项更改通知。

     

...

     

确保每个AppDomain只调用一次Start

因此,在您的应用启动中的某处放置一个Start()电话。因为这看起来像一种测试方法,可能采用[ClassInitialize]装饰方法。