我目前正在使用IConfigurationBuilder.AddAzureKeyVault(keyVaultEndpoint, new DefaultAzureCredential());将Azure密钥库秘密添加到我的dotnet 6应用程序中。
每当我解析var configuration = serviceProvider.GetRequiredService<IConfiguration>();的一个实例时,我就会得到IConfiguration的一个版本,我可以使用该版本来访问跨提供程序的所有密钥。
public static T GetOptions<T>(this IServiceCollection services, string sectionName)
where T : new()
{
using var serviceProvider = services.BuildServiceProvider();
var configuration = serviceProvider.GetRequiredService<IConfiguration>();
var section = configuration.GetSection(sectionName);
var options = new T();
section.Bind(options);
return options;
}但是,当我离开上面的方法时,IConfiguration的实例显然会被释放,并收到以下异常:
( System.ThrowHelper.ThrowObjectDisposedException(ExceptionResource资源处的
)
在Azure.Extensions.AspNetCore.Configuration.Secrets.AzureKeyVaultConfigurationProvider.Dispose(Boolean处理)在Azure.Extensions.AspNetCore.Configuration.Secrets.AzureKeyVaultConfigurationProvider.Dispose()在Microsoft.Extensions.Configuration.ConfigurationManager.DisposeRegistrationsAndProvidersUnsynchronized() at Microsoft.Extensions.Configuration.ConfigurationManager.Dispose()
在Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.Dispose() at Microsoft.Extensions.DependencyInjection.ServiceProvider.Dispose()
我假设IConfiguration是IServiceCollection中的单身汉,但是为什么会被处理掉呢?在配置对象时,为什么CancellationTokenSource为空?
发布于 2021-12-17 12:37:06
,但是为什么会被处理掉呢
您正在构建和处理整个服务提供者,这将导致处理它创建/拥有的所有东西(实现IDisposable):
var services = new ServiceCollection();
services.AddSingleton<MyDisposable>();
// note that changing to services.AddSingleton(new MyDisposable()); will change behaviour of the program
var sp = services.BuildServiceProvider();
var myDisposable = sp.GetRequiredService<MyDisposable>();
sp.Dispose();
Console.WriteLine(myDisposable.Disposed); // prints True
public class MyDisposable : IDisposable
{
public bool Disposed { get; set; }
public void Dispose()
{
Disposed = true;
}
}通常,您应该避免多次构建ServiceProvider,并且应该在需要时使用现有的API来获得配置。但是,如果没有其余的代码,就很难知道如何更改/重构GetOptions。
https://stackoverflow.com/questions/70392956
复制相似问题