Program.cs 中下面的代码
app.Lifetime.ApplicationStopping.Register(async () =>
{
await app.Services.GetRequiredService<IRedisDatabase>().RemoveAsync(blogPostCacheKey);
await app.Services.GetRequiredService<IRedisClientFactory>()
.GetRedisClient("redis-postbody")
.GetDbFromConfiguration()
.RemoveAsync(postBodyCacheKey);
});
在运行时会报错,错误信息如下
The active test run was aborted. Reason: Test host process crashed : Unhandled exception. System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'IServiceProvider'.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ThrowHelper.ThrowObjectDisposedException()
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(ServiceIdentifier serviceIdentifier, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
请问如何解决这个问题?
app.Lifetime.ApplicationStopping.Register(async () 不要异步. 它接受的是一个action. 内部callback 这个action的时候不会判断是不是返回了Task, 要不要await.
app.Lifetime.ApplicationStopping.Register( ()=>{
....RemoveAsync().GetAwaiter().GetResult(); 差不多这样子.
})
或者
await app.RunAsync()
// cleanup
await app.Service.....RemoveAsync(); 这样也行. 只要app没有dispose, 就都能用.
没注意到后面用的是 app.Run(),改为 app.RunAsync() 解决了
await app.RunAsync();
app.Lifetime.ApplicationStopping.Register(() =>
{
app.Services.GetRequiredService<IRedisDatabase>().RemoveAsync(blogPostCacheKey).Wait();
app.Services.GetRequiredService<IRedisClientFactory>()
.GetRedisClient("redis-postbody")
.GetDbFromConfiguration()
.RemoveAsync(postBodyCacheKey).Wait();
});