使用HotChocolate.AspNetCore与GraphQL时避免DbContext已释放问题求助
大家好,我现在卡在一个.NET Core+GraphQL的bug上,用的是HotChocolate.AspNetCore作为GraphQL服务器库。我写了个简单的查询接口用来返回联系人列表,第一次调用的时候能拿到正常响应,查询语句是这样的:
query { all { id name email } }
但第二次再调用这个查询时,直接报错了,错误信息如下:
Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances
我自己查了一些相关内容尝试解决,但还是没搞定,想请教下大家有没有遇到过类似的问题,应该怎么解决这个DbContext提前被释放的问题?
我自己梳理了几个可能的排查方向,也希望大家能给点建议:
- 会不会是DbContext的生命周期配置有问题?我目前是按默认的Scoped方式注册的,但会不会和GraphQL请求的生命周期不匹配?
- 我的Resolver方法是不是有异步处理的疏漏?比如返回的是延迟执行的枚举,而不是提前加载好的内存列表?
- 有没有可能我在某个地方不小心手动释放了DbContext?不过我印象里没写过Dispose调用或者using包裹DbContext的代码...
麻烦大家帮忙看看,谢谢啦!
备注:内容来源于stack exchange,提问作者Michael Rosario

