As the name suggests, the
Application_Start
event fires when the application starts. It doesn't run again until the application is restarted.
It will also potentially run
before any user has logged in, which would mean you wouldn't have a cookie value.
According to
the documentation[
^], you can safely call
SqlDependency.Start
multiple times for the same connection, and only one listener will start for each connection string. So the simplest solution is to move your code to the
Application_BeginRequest
event instead:
protected void Application_BeginRequest(object sender, EventArgs e)
{
var cookie = HttpContext.Current.Request.Cookies["zone"];
if (cookie == null || string.IsNullOrEmpty(cookie.Value)) return;
var connectionStringSetting = WebConfigurationManager.ConnectionStrings[cookie.Value];
if (connectionStringSetting == null) return;
string sqlConnectionString = connectionStringSetting.ConnectionString;
if (string.IsNullOrEmpty(sqlConnectionString)) return;
if (sqlConnectionString.StartsWith("metadata", StringComparison.OrdinalIgnoreCase))
{
var efBuilder = new System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder(sqlConnectionString);
sqlConnectionString = efBuilder.ProviderConnectionString;
}
SqlDependency.Start(sqlConnectionString);
}