在自定义ASP.NET Core配置提供程序中停止SqlDependency

时间:2019-01-07 10:00:55

标签: c# sql-server asp.net-core

我已经按照此处的说明编写了一个自定义配置提供程序,以从数据库表中加载ASP.NET Core配置:

ASP.Net Custom Configuration Provider

如果数据库中的值发生更改,我的提供程序将使用SqlDependency重新加载配置。

SqlDependency的{​​{3}}指出:

  

必须为每个Start调用调用Stop方法。给定的侦听器仅在收到与启动请求相同数量的停止请求时才完全关闭。

我不确定如何在ASP.NET Core的自定义配置提供程序中执行此操作。

我们在这里输入代码:

DbConfigurationSource

基本上是IDbProvider的容器,用于处理从数据库中检索数据

public class DbConfigurationSource : IConfigurationSource
{
    /// <summary>
    /// Used to access the contents of the file.
    /// </summary>
    public virtual IDbProvider DbProvider { get; set; }


    /// <summary>
    /// Determines whether the source will be loaded if the underlying data changes.
    /// </summary>
    public virtual bool ReloadOnChange { get; set; }

    /// <summary>
    /// Will be called if an uncaught exception occurs in FileConfigurationProvider.Load.
    /// </summary>
    public Action<DbLoadExceptionContext> OnLoadException { get; set; }

    public IConfigurationProvider Build(IConfigurationBuilder builder)
    {
        return new DbConfigurationProvider(this);
    }
}

DbConfigurationDataProvider

这是创建和监视SqlDependency并从数据库中加载数据的类。这也是我要Dispose() Stop()进行SqlDependency通话的地方。当前未调用Dispose()

public class DbConfigurationDataProvider : IDbProvider, IDisposable
{        
    private readonly string _applicationName;
    private readonly string _connectionString;

    private ConfigurationReloadToken _reloadToken;

    public DbConfigurationDataProvider(string applicationName, string connectionString)
    {
        if (string.IsNullOrWhiteSpace(applicationName))
        {
            throw new ArgumentNullException(nameof(applicationName));
        }

        if (string.IsNullOrWhiteSpace(connectionString))
        {
            throw new ArgumentNullException(nameof(connectionString));
        }

        _applicationName = applicationName;
        _connectionString = connectionString;

        _reloadToken = new ConfigurationReloadToken();

        SqlDependency.Start(_connectionString);
    }

    void OnDependencyChange(object sender, SqlNotificationEventArgs e)
    {
        var dependency = (SqlDependency)sender;
        dependency.OnChange -= OnDependencyChange;

        var previousToken = Interlocked.Exchange(
            ref _reloadToken,
            new ConfigurationReloadToken());

        previousToken.OnReload();
    }

    public IChangeToken Watch()
    {
        return _reloadToken;
    }

    public List<ApplicationSettingDto> GetData()
    {
        var settings = new List<ApplicationSettingDto>();

        var sql = "select parameter, value from dbo.settingsTable where application = @application";

        using (var connection = new SqlConnection(_connectionString))
        {
            using (var command = new SqlCommand(sql, connection))
            {
                command.Parameters.AddWithValue("application", _applicationName);

                var dependency = new SqlDependency(command);

                // Subscribe to the SqlDependency event.  
                dependency.OnChange += OnDependencyChange;

                connection.Open();

                using (var reader = command.ExecuteReader())
                {
                    var keyIndex = reader.GetOrdinal("parameter");
                    var valueIndex = reader.GetOrdinal("value");

                    while (reader.Read())
                    {
                        settings.Add(new ApplicationSettingDto
                            {Key = reader.GetString(keyIndex), Value = reader.GetString(valueIndex)});
                    }
                }
            }
        }

        Debug.WriteLine($"{DateTime.Now}: {settings.Count} settings loaded");

        return settings;
    }

    public void Dispose()
    {
        SqlDependency.Stop(_connectionString);
        Debug.WriteLine($"{nameof(WhsConfigurationProvider)} Disposed");
    }
}

DbConfigurationProvider

此类监视changeToken中的DbConfigurationDataProvider并将新配置发布到应用程序。

public class DbConfigurationProvider : ConfigurationProvider
{
    private DbConfigurationSource Source { get; }

    public DbConfigurationProvider(DbConfigurationSource source)
    {
        Source = source ?? throw new ArgumentNullException(nameof(source));

        if (Source.ReloadOnChange && Source.DbProvider != null)
        {
            ChangeToken.OnChange(
                () => Source.DbProvider.Watch(),
                () =>
                {                        
                    Load(reload: true);
                });                
        }           
    }

    private void Load(bool reload)
    {
        // Always create new Data on reload to drop old keys
        if (reload)
        {
            Data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        }

        var settings = Source.DbProvider.GetData();

        try
        {
            Load(settings);
        }
        catch (Exception e)
        {
            HandleException(e);
        }

        OnReload();
    }

    public override void Load()
    {
        Load(reload: false);
    }

    public void Load(List<ApplicationSettingDto> settings)
    {
        Data = settings.ToDictionary(s => s.Key, s => s.Value, StringComparer.OrdinalIgnoreCase);                       
    }

    private void HandleException(Exception e)
    {
            // Removed for brevity
    }     
}

DbConfigurationExtensions

调用扩展方法来设置所有内容。

public static class DbConfigurationExtensions
{
    public static IConfigurationBuilder AddDbConfiguration(this IConfigurationBuilder builder, IConfiguration config, string applicationName = "")
    {
        if (string.IsNullOrWhiteSpace(applicationName))
        {
            applicationName = config.GetValue<string>("ApplicationName");
        }

        // DB Server and Catalog loaded from Environment Variables for now
        var server = config.GetValue<string>("DbConfigurationServer");
        var database = config.GetValue<string>("DbConfigurationDatabase");

        if (string.IsNullOrWhiteSpace(server))
        {
            // Removed for brevity
        }

        if (string.IsNullOrWhiteSpace(database))
        {
            // Removed for brevity
        }

        var sqlBuilder = new SqlConnectionStringBuilder
        {
            DataSource = server,
            InitialCatalog = database,
            IntegratedSecurity = true
        };

        return builder.Add(new DbConfigurationSource
        {
             DbProvider = new DbConfigurationDataProvider(applicationName, sqlBuilder.ToString()),                
             ReloadOnChange = true
        } );
    }
}

最后,调用整个过程:

public class Program
{
    public static void Main(string[] args)
    {                        
        CreateWebHostBuilder(args).Build().Run();            
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
    {
        config.AddDbConfiguration(hostingContext.Configuration, "TestApp");            
    }).UseStartup<Startup>();
}

总结:如何确保在Dispose()类中调用DbConfigurationDataProvider方法?

到目前为止,我发现的唯一信息是从这里: documentation

其中介绍了如何处置对象:

  1. 在using语句内的代码块(不适用)
  2. 请求结束时(不适用)
  3. 使用DI容器(不适用-我不认为吗?)
  4. 应用程序结束时 <-听起来很有希望

选项4如下:

public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime,
                        SingletonAddedManually toDispose)
{
        applicationLifetime.ApplicationStopping.Register(OnShutdown, toDispose);

         // configure middleware etc
}

private void OnShutdown(object toDispose)
{
    ((IDisposable)toDispose).Dispose();
}
在我的情况下,

SingletonAddedManually将是DbConfigurationDataProvider类,但这在Startup类的范围之外。

有关IApplicationLifetime界面的更多信息:

https://andrewlock.net/four-ways-to-dispose-idisposables-in-asp-net-core/

编辑
这个例子甚至都没有打扰SqlDependency.Stop(),也许不是那么重要吗?

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/web-host?view=aspnetcore-2.2

1 个答案:

答案 0 :(得分:0)

执行此操作的“适当” 方法是让配置提供程序可抛弃,然后处置所有SqlDependency对象,作为配置提供程序处置的一部分。

不幸的是,在2.x中,配置框架不支持一次性提供程序。但是,这可能会作为aspnet/Extensions#786aspnet/Extensions#861的一部分进行更改。

由于我参与了此开发工作,因此我很自豪地宣布从3.0开始,将支持一次性配置提供程序

Microsoft.Extensions.Configuration 3.0中,一次性处置提供者将在处置配置根目录后被适当处置。 (web)主机被处置后,配置根将被处置在ASP.NET Core 3.0中。因此,最后,您的一次性配置提供程序将得到妥善处理,并且不再泄漏任何东西。