首页 新闻 会员 周边 捐助

.NET: app.Lifetime.ApplicationStopping.Register 中的依赖注入问题

0
悬赏园豆:50 [已解决问题] 解决于 2025-12-12 10:36

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)

请问如何解决这个问题?

dudu的主页 dudu | 高人七级 | 园豆:24143
提问于:2025-12-10 19:49
< >
分享
最佳答案
0

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, 就都能用.

收获园豆:30
czd890 | 专家六级 |园豆:14718 | 2025-12-11 10:26

没注意到后面用的是 app.Run(),改为 app.RunAsync() 解决了

await app.RunAsync();
dudu | 园豆:24143 (高人七级) | 2025-12-12 10:35
其他回答(1)
0

这里得用同步方式,像这样

app.Lifetime.ApplicationStopping.Register(() =>
{

    app.Services.GetRequiredService<IRedisDatabase>().RemoveAsync(blogPostCacheKey).Wait();
    app.Services.GetRequiredService<IRedisClientFactory>()
        .GetRedisClient("redis-postbody")
        .GetDbFromConfiguration()
        .RemoveAsync(postBodyCacheKey).Wait();
});
收获园豆:20
青争竹马 | 园豆:5872 (大侠五级) | 2025-12-12 09:53
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册