如何将DI存储库转换为Type-class?

问题描述 投票:0回答:1

需要一些帮助,请...

我正在查看示例“graphql-dotnet / server”,其中公开的对象只包含普通属性。但是,如果我需要解析属性并从存储库中获取数据,我怎样才能获得Type-class中的存储库类?

示例:示例中有一个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-dotnet / server”项目中的MessageType类?但它适用于“graphql-dotnet / examples”项目。

最好,马格努斯

dependency-injection graphql graphql-dotnet
1个回答
0
投票

要使用DI,您需要在Schema类的构造函数中传递依赖项解析器。默认解析器使用Activator.CreateInstance,因此您必须教它正在使用的Container。

services.AddSingleton<IDependencyResolver>(
  s => new FuncDependencyResolver(s.GetRequiredService));

IDependecyResolver是graphql-dotnet项目中的一个接口。

public class StarWarsSchema : Schema
{
    public StarWarsSchema(IDependencyResolver resolver)
        : base(resolver)
    {
        Query = resolver.Resolve<StarWarsQuery>();
        Mutation = resolver.Resolve<StarWarsMutation>();
    }
}

https://github.com/graphql-dotnet/examples/blob/bcf46c5c502f8ce75022c50b9b23792e5146f6d2/src/AspNetCore/Example/Startup.cs#L20

https://github.com/graphql-dotnet/examples/blob/bcf46c5c502f8ce75022c50b9b23792e5146f6d2/src/StarWars/StarWarsSchema.cs#L6-L14

© www.soinside.com 2019 - 2024. All rights reserved.