c# - GraphQL 服务的依赖注入
问题描述
我正在使用带有 HotChocolate 包的 NET5 webapi 并尝试注入服务。我遵循了此处记录的标准和基于方法的方法,但是它根本不起作用。我得到的只是以下消息:
{
"errors": [
{
"message": "Unexpected Execution Error",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"tests"
]
}
],
"data": {
"tests": null
}
}
我的查询:
query{
tests {
id
}
}
我的代码目前反映了记录的方法方法。
在启动时:
services
.AddSingleton<ITestService, TestService>()
.AddGraphQLServer()
.AddDefaultTransactionScopeHandler()
.AddQueryType<Queries>()
.AddMutationType<Mutations>()
.AddFiltering()
.AddSorting()
.AddProjections()
.AddType<Test>();
查询设置:
[UseProjection]
[UseFiltering]
[UseSorting]
public IQueryable<Test> GetTests([Service] ITestService testService) => testService.GetTests();
我的测试服务:
private readonly IDbContextFactory<TestDbContext> contextFactory;
public TestService(IDbContextFactory<TestDbContext> contextFactory)
{
this.contextFactory = contextFactory;
}
public IQueryable<Test> GetTests()
{
using var context = contextFactory.CreateDbContext();
return context.Test;
}
我确定我缺少一些简单的东西来完成这项工作。
解决方案
您的数据库上下文已处理。GetTests 中的使用适用于此方法。在此方法结束时,db 上下文被释放并返回一个 Queryable。一旦执行引擎执行了 Queryable,就会抛出异常
查看 HotChocolate 的 EF Core 集成: https ://chillicream.com/docs/hotchocolate/integrations/entity-framework
推荐阅读
- flutter - Flutter List UI 未正确更新
- html - 如何使用 css 在 div 元素的右侧添加 box-shadow?
- excel - 遍历范围,复制某些单元格,将格式粘贴到另一个工作表
- java - java,我的线程被终止,没有任何异常或可抛出,为什么?
- javascript - 如何在 ES6 中对地图进行排序
- node.js - 在 Teams Bot 中出现多个 404 和 405 错误
- c# - Redis - Moving from IIS session state
- javascript - NodeJs 中的 SOAP 请求返回 500 内部服务器错误
- eigen - 如何使用条件有效地向量化多项式计算(屋顶线模型)
- python - 如何正确地将回调绑定到 Python Kivy 库中循环中的每个元素