From 3a90dd3d8ad1a9ee50fc90dc3baff52394721ffc Mon Sep 17 00:00:00 2001 From: martincostello Date: Sun, 17 Oct 2021 18:41:54 +0100 Subject: [PATCH] Prevent ObjectDisposedException if disposed twice Prevent ObjectDisposeException if AzureKeyVaultConfigurationProvider is disposed of more than once. See dotnet/aspnetcore#37631. --- .../src/AzureKeyVaultConfigurationProvider.cs | 10 ++++++++-- .../tests/AzureKeyVaultConfigurationTests.cs | 15 +++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/sdk/extensions/Azure.Extensions.AspNetCore.Configuration.Secrets/src/AzureKeyVaultConfigurationProvider.cs b/sdk/extensions/Azure.Extensions.AspNetCore.Configuration.Secrets/src/AzureKeyVaultConfigurationProvider.cs index b14a758899be2..9d8a3ba0b3d72 100644 --- a/sdk/extensions/Azure.Extensions.AspNetCore.Configuration.Secrets/src/AzureKeyVaultConfigurationProvider.cs +++ b/sdk/extensions/Azure.Extensions.AspNetCore.Configuration.Secrets/src/AzureKeyVaultConfigurationProvider.cs @@ -23,6 +23,7 @@ public class AzureKeyVaultConfigurationProvider : ConfigurationProvider, IDispos private Dictionary _loadedSecrets; private Task _pollingTask; private readonly CancellationTokenSource _cancellationToken; + private bool _disposed; /// /// Creates a new instance of . @@ -148,8 +149,13 @@ protected virtual void Dispose(bool disposing) { if (disposing) { - _cancellationToken.Cancel(); - _cancellationToken.Dispose(); + if (!_disposed) + { + _cancellationToken.Cancel(); + _cancellationToken.Dispose(); + } + + _disposed = true; } } diff --git a/sdk/extensions/Azure.Extensions.AspNetCore.Configuration.Secrets/tests/AzureKeyVaultConfigurationTests.cs b/sdk/extensions/Azure.Extensions.AspNetCore.Configuration.Secrets/tests/AzureKeyVaultConfigurationTests.cs index fc184f7df3cc2..5946ee5686825 100644 --- a/sdk/extensions/Azure.Extensions.AspNetCore.Configuration.Secrets/tests/AzureKeyVaultConfigurationTests.cs +++ b/sdk/extensions/Azure.Extensions.AspNetCore.Configuration.Secrets/tests/AzureKeyVaultConfigurationTests.cs @@ -628,6 +628,21 @@ public void ConstructorThrowsForNegativeRefreshPeriodValue() Assert.Throws(() => new AzureKeyVaultConfigurationProvider(Mock.Of(), new AzureKeyVaultConfigurationOptions() { ReloadInterval = TimeSpan.FromMilliseconds(-1) })); } + [Test] + public void DisposeCanBeCalledMultipleTimes() + { + // Arrange + var client = new Mock(); + + using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManager() })) + { + provider.Dispose(); + + // Act & Assert + Assert.DoesNotThrow(() => provider.Dispose()); + } + } + private class EndsWithOneKeyVaultSecretManager : KeyVaultSecretManager { public override bool Load(SecretProperties secret)