这里需要帮助..。
我正在查看示例"graphql-dotnet/server“,其中公开的对象只包含普通属性。但是,如果我需要解析一个属性并从存储库中获取数据,我如何才能获得Type类中的respository类?
示例:该示例有一个公开“消息”的ChatQuery。
public ChatQuery(IChat chat)
{
Field<ListGraphType<MessageType>>("messages", resolve: context => chat.AllMessages.Take(100));
}实例"chat“是此处的存储库,它通过chat.AllMessages为数据(消息)提供服务。
比方说,一条消息有一个观众列表。然后,我需要从存储库中解析该列表。这是在另一个示例"graphql-dotnet/examples“中完成的,其中"StarWars/Types/StarWarsCharacter.cs”有一个好友列表,"StarWars/Types/HumanType“在构造函数中插入了存储库(StarWarsData),可以在”朋友“的解析方法中使用:
public class HumanType : ObjectGraphType<Human>
{
public HumanType(StarWarsData data)
{
Name = "Human";
Field(h => h.Id).Description("The id of the human.");
Field(h => h.Name, nullable: true).Description("The name of the human.");
Field<ListGraphType<CharacterInterface>>(
"friends",
resolve: context => data.GetFriends(context.Source)
);
Field<ListGraphType<EpisodeEnum>>("appearsIn", "Which movie they appear in.");
Field(h => h.HomePlanet, nullable: true).Description("The home planet of the human.");
Interface<CharacterInterface>();
}
}但是,在服务器示例中做同样的事情是行不通的。
public class MessageType : ObjectGraphType<Message>
{
public MessageType(IChat chat)
{
Field(o => o.Content);
Field(o => o.SentAt);
Field(o => o.From, false, typeof(MessageFromType)).Resolve(ResolveFrom);
Field<ListGraphType<Viewer>>(
"viewers",
resolve: context => chat.GetViewers(context.Source)
);
}
private MessageFrom ResolveFrom(ResolveFieldContext<Message> context)
{
var message = context.Source;
return message.From;
}
}当我将聊天存储库添加到MessageType中的构造函数时,它会失败。
--我在这里显然遗漏了一些东西;为什么依赖注入没有将聊天实例注入到“graphql/server”项目中的MessageType类中?但它适用于“graphql/examples”项目.
最好,马格纳斯
发布于 2018-06-03 15:01:11
要使用DI,需要在Schema类的构造函数中传递依赖项解析器。默认的解析器使用Activator.CreateInstance,因此您必须教它您正在使用的容器。
services.AddSingleton<IDependencyResolver>(
s => new FuncDependencyResolver(s.GetRequiredService));IDependecyResolver是graphql项目中的一个接口。
public class StarWarsSchema : Schema
{
public StarWarsSchema(IDependencyResolver resolver)
: base(resolver)
{
Query = resolver.Resolve<StarWarsQuery>();
Mutation = resolver.Resolve<StarWarsMutation>();
}
}https://stackoverflow.com/questions/50643549
复制相似问题