Git Product home page Git Product logo

examples's Introduction

GraphQL for .NET

License codecov Nuget Nuget GitHub Release Date GitHub commits since latest release (by date) Size

GitHub contributors Activity Activity Activity

❤️ Become a backer! ❤️ Backers on Open Collective Sponsors on Open Collective
💲 Get paid for contributing! 💲 GitHub issues by-label GitHub closed issues by-label

This is an implementation of Facebook's GraphQL in .NET.

Now the specification is being developed by the GraphQL Foundation.

This project uses a lexer/parser originally written by Marek Magdziak and released with a MIT license. Thank you Marek!

Provides the following packages:

Package Downloads NuGet Latest
GraphQL Nuget Nuget
GraphQL.SystemTextJson Nuget Nuget
GraphQL.NewtonsoftJson Nuget Nuget
GraphQL.MemoryCache Nuget Nuget
GraphQL.DataLoader Nuget Nuget
GraphQL.MicrosoftDI Nuget Nuget

You can get all preview versions from GitHub Packages. Note that GitHub requires authentication to consume the feed. See here.

Documentation

  1. http://graphql-dotnet.github.io - documentation site that is built from the docs folder in the master branch.
  2. https://graphql.org/learn - learn about GraphQL, how it works, and how to use it.

Debugging

All packages generated from this repository come with embedded pdb and support Source Link. If you are having difficulty understanding how the code works or have encountered an error, then it is just enough to enable Source Link in your IDE settings. Then you can debug GraphQL.NET source code as if it were part of your project.

Installation

1. GraphQL.NET engine

This is the main package, the heart of the repository in which you can find all the necessary classes for GraphQL request processing.

> dotnet add package GraphQL

2. Serialization

For serialized results, you'll need an IGraphQLSerializer implementation. We provide several serializers (or you can bring your own).

> dotnet add package GraphQL.SystemTextJson
> dotnet add package GraphQL.NewtonsoftJson

Note: You can use GraphQL.NewtonsoftJson with .NET Core 3+, just be aware it lacks async writing capabilities so writing to an ASP.NET Core 3.0 HttpResponse.Body will require you to set AllowSynchronousIO to true as per this announcement; which isn't recommended.

3. Document Caching

The recommended way to setup caching layer (for caching of parsed GraphQL documents) is to inherit from IConfigureExecution interface and register your class as its implementation. We provide in-memory implementation on top of Microsoft.Extensions.Caching.Memory package.

> dotnet add package GraphQL.MemoryCache

For more information see Document Caching.

4. DataLoader

DataLoader is a generic utility to be used as part of your application's data fetching layer to provide a simplified and consistent API over various remote data sources such as databases or web services via batching and caching.

> dotnet add package GraphQL.DataLoader

For more information see DataLoader.

Note: Prior to version 4, the contents of this package was part of the main GraphQL.NET package.

5. Subscriptions

DocumentExecuter can handle subscriptions as well as queries and mutations. For more information see Subscriptions.

6. Advanced Dependency Injection

Also we provide some extra classes for advanced dependency injection usage on top of Microsoft.Extensions.DependencyInjection.Abstractions package.

> dotnet add package GraphQL.MicrosoftDI

For more information see Thread safety with scoped services.

Examples

https://github.com/graphql-dotnet/examples

You can also try an example of GraphQL demo server inside this repo - GraphQL.Harness. It supports the popular IDEs for managing GraphQL requests and exploring GraphQL schema:

Ahead-of-time compilation

GraphQL.NET supports ahead-of-time (AOT) compilation for execution of code-first schemas with .NET 7. This allows for use within iOS and Android apps, as well as other environments where such features as JIT compilation or dynamic code generation are not available. It may be necessary to explicitly instruct the AOT compiler to include the .NET types necessary for your schema to operate correctly. Of particular note, your query, mutation and subscription types' constructors may be trimmed; register them in your DI engine to prevent this. Also, Field(x => x.MyField) for enumeration values will require manually adding a mapping reference via RegisterTypeMapping<MyEnum, EnumerationGraphType<MyEnum>>(). Please see the GraphQL.AotCompilationSample for a simple demonstration of AOT compilation. Schema-first and type-first schemas have additional limtations and configuration requirements. AOT compilation has not been tested with frameworks other than .NET 7 on Windows and Linux (e.g. Xamarin).

Training

Upgrade Guides

You can see the changes in public APIs using fuget.org.

Basic Usage

Define your schema with a top level query object then execute that query.

Fully-featured examples can be found here.

Hello World

using System;
using System.Threading.Tasks;
using GraphQL;
using GraphQL.Types;
using GraphQL.SystemTextJson; // First add PackageReference to GraphQL.SystemTextJson

var schema = Schema.For(@"
  type Query {
    hello: String
  }
");

var root = new { Hello = "Hello World!" };
var json = await schema.ExecuteAsync(_ =>
{
  _.Query = "{ hello }";
  _.Root = root;
});

Console.WriteLine(json);

Schema First Approach

This example uses the GraphQL schema language. See the documentation for more examples and information.

public class Droid
{
  public string Id { get; set; }
  public string Name { get; set; }
}

public class Query
{
  [GraphQLMetadata("droid")]
  public Droid GetDroid()
  {
    return new Droid { Id = "123", Name = "R2-D2" };
  }
}

var schema = Schema.For(@"
  type Droid {
    id: ID
    name: String
  }

  type Query {
    droid: Droid
  }
", _ => {
    _.Types.Include<Query>();
});

var json = await schema.ExecuteAsync(_ =>
{
  _.Query = "{ droid { id name } }";
});

Parameters

public class Droid
{
  public string Id { get; set; }
  public string Name { get; set; }
}

public class Query
{
  private List<Droid> _droids = new List<Droid>
  {
    new Droid { Id = "123", Name = "R2-D2" }
  };

  [GraphQLMetadata("droid")]
  public Droid GetDroid(string id)
  {
    return _droids.FirstOrDefault(x => x.Id == id);
  }
}

var schema = Schema.For(@"
  type Droid {
    id: ID
    name: String
  }

  type Query {
    droid(id: ID): Droid
  }
", _ => {
    _.Types.Include<Query>();
});

var json = await schema.ExecuteAsync(_ =>
{
  _.Query = $"{{ droid(id: \"123\") {{ id name }} }}";
});

Roadmap

Grammar / AST

Operation Execution

  • Scalars
  • Objects
  • Lists of objects/interfaces
  • Interfaces
  • Unions
  • Arguments
  • Variables
  • Fragments
  • Directives
    • Include
    • Skip
    • Custom
  • Enumerations
  • Input Objects
  • Mutations
  • Subscriptions
  • Async execution

Validation

  • Arguments of correct type
  • Default values of correct type
  • Fields on correct type
  • Fragments on composite types
  • Known argument names
  • Known directives
  • Known fragment names
  • Known type names
  • Lone anonymous operations
  • No fragment cycles
  • No undefined variables
  • No unused fragments
  • No unused variables
  • Overlapping fields can be merged
  • Possible fragment spreads
  • Provide non-null arguments
  • Scalar leafs
  • Unique argument names
  • Unique directives per location
  • Unique fragment names
  • Unique input field names
  • Unique operation names
  • Unique variable names
  • Variables are input types
  • Variables in allowed position
  • Single root field

Schema Introspection

GraphQL.NET supports introspection schema from October 2021 spec with some additional experimental introspection extensions.

Publishing NuGet packages

The package publishing process is automated with GitHub Actions.

After your PR is merged into master or develop, preview packages are published to GitHub Packages.

Stable versions of packages are published to NuGet when a release is created.

Contributors

This project exists thanks to all the people who contribute.

PRs are welcome! Looking for something to work on? The list of open issues is a great place to start. You can help the project simply respond to some of the asked questions.

The default branch is master. It is designed for non-breaking changes, that is to publish versions 7.x.x. If you have a PR with some breaking changes, then please target it to the develop branch that tracks changes for v8.0.0.

Backers

Thank you to all our backers! 🙏 Become a backer.

Contributions are very much appreciated and are used to support the project primarily via bounties paid directly to contributors to the project. Please help us to express gratitude to those individuals who devote time and energy to contributing to this project by supporting their efforts in a tangible means. A list of the outstanding issues to which we are sponsoring via bounties can be found here.

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. Become a sponsor.

examples's People

Contributors

dependabot[bot] avatar joemcbride avatar kant2002 avatar madslundt avatar revazashvili avatar shane32 avatar stefanschoof avatar sungam3r avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

examples's Issues

Calling REST multiple services

I have a microservice architecture with several REST services and dedicated databases for each service. I want to create a report that consist of data from multiple services. Can this lib be used for this case.
Scenario
Car service list all cars and order history list all orders for each car. Report shown below should list all recent 10 order against all the cars in the cars db.

image
image

Question:

  1. In the scheme how do I resolve orders? is it best to call the orders rest endpoint directly or use the database repository as the source.
  2. can this approach handle 10,000 cars and history?
  3. Is there an example of similar implementation I can use?

Startup uses obsolete methods

In some examples startup is using obsolete methods.
There was changes recently to simply add the pragma statement to ignore compiler warnings. Why?
Why not just use the correct methods?
This was also called out in the PR when this was merged only hours ago.
Also it would help if the Obsolete attributes also contained the information indicating which alternatives should be used instead.
I'm still struggling to find the right way to register these components in .NET 6 for a webapi project.

GraphQL.MicrosoftDI implementation for version 5.3.3

https://github.com/graphql-dotnet/examples/blob/master/src/AspNetCore/Example/Example.csproj

The implementation has been changed after GraphQL.MicrosoftDIversion 5.3.3 example implements
public static IServiceCollection AddGraphQL(this IServiceCollection services, Action<IGraphQLBuilder>? configure)
while the current version implements following GraphQL version 5.1.1
public static IGraphQLBuilder AddGraphQL(this IServiceCollection services)

how can we add all previous dependencies as

  services.AddGraphQL(b => b
                .AddHttpMiddleware<ISchema>()
                .AddUserContextBuilder(httpContext => new GraphQLUserContext { User = httpContext.User })
                .AddSystemTextJson()
                .AddErrorInfoProvider(opt => opt.ExposeExceptionStackTrace = true)
                .AddSchema<StarWarsSchema>()
                .AddGraphTypes(typeof(StarWarsSchema).Assembly));

Method AddGraphQL is [Obsolete] as well, previous support for GraphQL.MicrosoftDI.GraphQLBuilderExtensions.AddGraphQL(builder.Services) is also not available in latest vrsion.
Can anyone please guide

Cannot retrieve schema but queries work in prototype

I downloaded the example app and it works properly, submitting queries and manipulations and viewing the schema. I then created my own prototype following the example app framework with a new AspNetCore web api and my own types. When I run my prototype, the UI Playground works to submit queries and mutations against my service (and I can put a breakpoint in the service and manipulate the return result values). However, there is no schema displayed in the viewer of the UI Playground. I'm not getting any error messages and I can't determine if this is an error in the Playground client app or if this is an issue in my prototype service. What can I do to identify the cause of this behavior?

Authentication/Authorization in core 2.2 and core 3.0

Sorry for cluttering up issues here, but this seems like the place where this is good dialog about this project. I plan on updating my Pluralsight course soon (after core 3.1 ships) on asp.net core and React and I want to include a short section on integration with React using this project. I'm in no hurry to get a good answer, but want to make sure I understand what is a best practice way I should do things. For now, I'm sticking to core 2.2 because I gave up on the develop branch (until it is stable enough for me, my issue, I'm sure it's fine).

So, I've JwtToken's working as I want and in standard controllers, the attributes Authorize and Roles are working correctly and I want similar functionality in GraphQL. In my "Type" file, for example, I want to only show the email address if the user is authenticated and has a role of admin. What I've done is modify the Field definition from:

Field(t => t.Email).Description("users unique email");

to

Field<StringGraphType>("email", resolve: context =>
{
    var isAuthenticated = GetAuthStatus.Get(context.UserContext as ClaimsPrincipal, out var username, out var isAdmin);
    return isAuthenticated && isAdmin ? context.Source.Email + ":" + username : "<email blocked>:" + username;
});

And, I've created a simple getAuthStatus class as follows:

public static class GetAuthStatus
{
    public static bool Get(ClaimsPrincipal user, out string username, out bool isAdmin)
    {
        var isAuthenticated = ((ClaimsIdentity)user.Identity).IsAuthenticated;
        if (isAuthenticated)
        {
            username = user.Identity.Name;
            isAdmin = ((ClaimsIdentity)user.Identity).Claims.Any(a =>
                a.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" && a.Value == "Admin");
        }
        else
        {
            username = "";
            isAdmin = false;
        }
        return isAuthenticated;
    }
}

My solutions quite clunky. Is there either now (2.2) a hugely better way to do this, or in (3.0/3.1) is there a better way coming? My goal is to keep the code in the Types themselves as simple as possible.

Thanks

Add subscription to AspCoreCustom example

I cannot find any good examples where subscriptions are implemented in Asp.net core, using custom middleware and WebSocket. Can this be included in the AspCoreCustom example?

Outdated examples

The code were given in graphql-dotnet 3.1.3, whereas the current version is 4.5.0.

Alternative to registering all GraphType

Is there any better alternative than registering all graphql types in following way? As with growing GraphType it will be a long list. Sorry that I had to post here. As stackoverflow doesn't allow external link.

container.Singleton(new StarWarsData());
container.Register();
container.Register();
container.Register();
container.Register();
container.Register();
container.Register();
container.Singleton(new StarWarsSchema(new FuncDependencyResolver(type => container.Get(type))));

Update examples to v5.0.0.

The examples are using the version 4.7.1 and the latest stable is 5.0.0. I updated my nuget packages and struggling now with diverse issues. Please update at least AppNetCoreController.

Bad Request error, after migrating API (from one based on the old aspnetcore example to the newer "example" repository)

Getting the following when trying to use the API.

{
  "version": {
    "major": 1,
    "minor": 1,
    "build": -1,
    "revision": -1,
    "majorRevision": -1,
    "minorRevision": -1
  },
  "content": {
    "headers": [
      {
        "key": "Content-Type",
        "value": [
          "application\/json; charset=utf-8"
        ]
      }
    ]
  },
  "statusCode": 400,
  "reasonPhrase": "Bad Request",
  "headers": [
    
  ],
  "requestMessage": {
    "version": {
      "major": 2,
      "minor": 0,
      "build": -1,
      "revision": -1,
      "majorRevision": -1,
      "minorRevision": -1
    },
    "content": null,
    "method": {
      "method": "GET"
    },
    "requestUri": null,
    "headers": [
      
    ],
    "properties": {
      
    }
  },
  "isSuccessStatusCode": false
}

It is quite vague as to what the cause of the error is. Is there something wrong with the setup of my queries / types? Or is it in my request? Is it about authentication? I just migrated the API project from one that's based on the old example, "example-aspnetcore", to one that's found in "examples".

I'm not sure which code to share, so I uploaded my API library at: https://github.com/jonasarcangel/GraphQLIssue

Examples AspNetWebApi solution does not compile

I had to make the following changes to get the project compiling -

C:\dev\github\graphql-dotnet\examples [master ≡ +0 ~3 -0 !]> git diff *
diff --git a/src/AspNetWebApi/Example/AspNetWebApi.csproj b/src/AspNetWebApi/Example/AspNetWebApi.csproj
index ea39c87..67a9c67 100644
--- a/src/AspNetWebApi/Example/AspNetWebApi.csproj
+++ b/src/AspNetWebApi/Example/AspNetWebApi.csproj
@@ -46,8 +46,8 @@
     <WarningLevel>4</WarningLevel>
   </PropertyGroup>
   <ItemGroup>
-    <Reference Include="GraphQL, Version=2.0.0.899, Culture=neutral, processorArchitecture=MSIL">
-      <HintPath>..\packages\GraphQL.2.0.0-alpha-899\lib\net45\GraphQL.dll</HintPath>
+    <Reference Include="GraphQL, Version=2.0.0.951, Culture=neutral, processorArchitecture=MSIL">
+      <HintPath>..\packages\GraphQL.2.0.0-alpha-951\lib\net45\GraphQL.dll</HintPath>
     </Reference>
     <Reference Include="GraphQL-Parser, Version=3.0.0.0, Culture=neutral, processorArchitecture=MSIL">
       <HintPath>..\packages\GraphQL-Parser.3.0.0\lib\net45\GraphQL-Parser.dll</HintPath>
diff --git a/src/AspNetWebApi/Example/packages.config b/src/AspNetWebApi/Example/packages.config
index a0d9122..b4ed96f 100644
--- a/src/AspNetWebApi/Example/packages.config
+++ b/src/AspNetWebApi/Example/packages.config
@@ -1,6 +1,6 @@
-<?xml version="1.0" encoding="utf-8"?>
+<EF><BB><BF><?xml version="1.0" encoding="utf-8"?>
 <packages>
-  <package id="GraphQL" version="2.0.0-alpha-927" targetFramework="net461" />
+  <package id="GraphQL" version="2.0.0-alpha-951" targetFramework="net461" />
   <package id="GraphQL-Parser" version="3.0.0" targetFramework="net461" />
   <package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" />
   <package id="Microsoft.AspNet.Razor" version="3.2.3" targetFramework="net45" />
@@ -30,4 +30,4 @@
   <package id="System.Reactive.Interfaces" version="3.1.1" targetFramework="net461" />
   <package id="System.Reactive.Linq" version="3.1.1" targetFramework="net461" />
   <package id="WebGrease" version="1.5.2" targetFramework="net45" />
-</packages>

+</packages>
\ No newline at end of file
diff --git a/src/StarWars/StarWars.csproj b/src/StarWars/StarWars.csproj
index f4c7130..970fce3 100644
--- a/src/StarWars/StarWars.csproj
+++ b/src/StarWars/StarWars.csproj
@@ -10,7 +10,7 @@
   </PropertyGroup>

   <ItemGroup>
-    <PackageReference Include="GraphQL" Version="2.0.0-alpha-947" />
+    <PackageReference Include="GraphQL" Version="2.0.0-alpha-951" />
   </ItemGroup>

 </Project>

Unable to inject schema when using more than one schema in Dependecy Injection.

Hi all,

Here, i am having a problem with Ischema, When i am using ISchema i need to define type of that but problem occurs when need to use multiple schema as we can define one schema type only at a time.

Here, i am sharing code with you.

private ISimpleContainer BuildContainer()
{
var container = new SimpleContainer();
container.Singleton(new DocumentExecuter());
container.Singleton(new DocumentWriter(true));

        container.Singleton(new StarWarsData());
        container.Register<StarWarsQuery>();
        container.Register<StarWarsMutation>();
        container.Register<HumanType>();
        container.Register<HumanInputType>();
        container.Register<DroidType>();
        container.Register<CharacterInterface>();

      /*As here i am adding ISchema as type so this is calling properly but ..*/
        container.Singleton<ISchema>(new StarWarsSchema(new FuncDependencyResolver(type => 
        container.Get(type))));

    /*When need to add another one then it is not calling let alone get executed...*/
        container.Singleton<ISchema>(new EpisodeSchema(new FuncDependencyResolver(type => 
        container.Get(type))));
   // following is the error, i am getting while executing this code...
 // Dictionary can not add multiple instnace of ISchema.



        return container;
    }

thanks

UseMemoryCache don't work

Hello! Im using GraphQL 7.1.1 Memory Cache package and register it in DI like that:
.UseMemoryCache(options => { options.SizeLimit = 1_000_000; options.SlidingExpiration = null; })

My sample resolve is:

 public class Query : ObjectGraphType<object>
    {
        public Query(IBusinessData data)
        {
            Name = "Query";
          Field<ListGraphType<EmailType>, IEnumerable<Emails>>("emails")
                .ResolveAsync(context => data.GetAutomappedValuesAsync<Emails>("Emails", "Emails", "", context.UserContext));
            

where GetAutomappedValuesAsync method is reading < 1MB data from web.

But every time i run query {emails {id}} GraphQL making web request instead of reading from cache.

What i have missed in configuring cache?

Issue running the sample

Hey! I forked this sample repo but when I run the API project the browser comes up with a blank screen.

I just started studying GraphQL and I would very much like to see a working API sample.

example is not working when running npm run webpack

Gets an error when running npm run webpack:

Child extract-text-webpack-plugin node_modules/extract-text-webpack-plugin/dist node_modules/css-loader/index.js!node_modules/graphiql/graphiql.css:
2 modules
Child extract-text-webpack-plugin node_modules/extract-text-webpack-plugin/dist node_modules/css-loader/index.js!app/app.css:
[0] ./node_modules/css-loader!./app/app.css 295 bytes {0} [built]
+ 1 hidden module
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] webpack: webpack --progress
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the [email protected] webpack script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\kim\AppData\Roaming\npm-cache_logs\2018-06-15T09_28_46_207Z-debug.log

need to add this in package.json inside the "dependencies" prop: "graphql": "^0.13.2",

Enum to int cast

I'm a .Net/C# newbie so I apologize if this is a waste of time.. I'm looking at the Star Wars example about using Enums.. and what I have is an input which a field that's an Enum.. and the class behind it stores it as an int.. like how the Character abstract has an array of ints for 'appearsIn'.. but when the GetArgument runs it crashes out due to not being able to find the conversion. Thoughts on what I may have done wrong?

I've trimmed the code down for this issue but here's an accurate representation:

    public class OriginationMutation : ObjectGraphType
    {
        public OriginationMutation()
        {
            Field<CreateApplicationResponseType>(
                "createApplication",
                arguments: new QueryArguments(new QueryArgument<NonNullGraphType<CreateApplicationInputType>> { Name = "application" }),
                resolve: context =>
                {
                    var application = context.GetArgument<CreateApplicationInput>("application");
                    var response = new CreateApplicationResponse();

                    return response;
                }
            );
        }
    }

public class CreateApplicationInputType : InputObjectGraphType<CreateApplicationInput>
    {
        public CreateApplicationInputType()
        {

            Field<NonNullGraphType<SubProductEnum>>("subProductId");

        }

    }

    public class CreateApplicationInput
    {
        public CreateApplicationInput()        {        }

        public int SubProductId { get; set; }
    }

public class SubProductEnum : EnumerationGraphType
    {
        public SubProductEnum()
        {
            Name = "SubProductEnum";
            Description = "Available products to apply for.";
            AddValue("PLEDGE", "Pledge", SubProducts.PLEDGE);
            AddValue("CREDIT_CARD", "Credit Card", SubProducts.CREDIT_CARD);
        }

    }
    public enum SubProducts
    {
        PLEDGE = 1009,
        CREDIT_CARD = 1013,
    }

The line that fails is:

var application = context.GetArgument<CreateApplicationInput>("application");

Could not find the conversion from Origination.Types.SubProductEnum to Int32

Unamapped Selection

image

I am getting while running this project. I just made one change to add a source o visual studio to look for GraphQL Package.

Also any project I try to run on GraphQl I am getting the same error.

Schema First Example

I think it would be wise to include a schema-first example in this repo. If someone approves, I will write up an example.

Updated Nugets to 2.2 and Version 3 preview - error in Middleware

Getting this error:

Severity Code Description Project File Line Suppression State
Error CS0266 Cannot implicitly convert type 'object' to 'System.Collections.Generic.IDictionary<string, object>'. An explicit conversion exists (are you missing a cast?) GraphQLMiddleware.cs Line 62

Is it possible to use two schema?

private ISimpleContainer BuildContainer()
{
var container = new SimpleContainer();
container.Singleton(new DocumentExecuter());
container.Singleton(new DocumentWriter(true));

        container.Register<EmphQuery>();
        container.Register<EmphMutation>();
        container.Register<EmphType>();
        container.Singleton<ISchema>(new EmphSchema(new FuncDependencyResolver(type => container.Get(type))));

        container.Register<DeptQuery>();
        container.Register<DeptType>();
        **container.Singleton<ISchema>(new DeptSchema(new FuncDependencyResolver(type => container.Get(type))));**

        return container;
    }

it throw an exception:
System.ArgumentException:“ An item with the same key has already been added

if i modify to:
container.Singleton<DeptSchema>(new DeptSchema(new FuncDependencyResolver(type => container.Get(type))));
it seems Invalid when i query dept

Example using subscriptions with ASP.NET Web API

Are there any examples/resources available on the topic of using subscriptions with ASP.NET Web API?

While creating a model for subscriptions is not a problem, connecting it with a transport layer seems to be quite a hassle.

AddUserContextBuilder error in .NET core 3.0

While attempting to update our application from .NET core 2.2 to 3.0 we got the following error:

The type 'xyz.Service.GraphQLUserContext' cannot be used as type parameter 'TUserContext' in the generic type or method 'GraphQLBuilderExtensions.AddUserContextBuilder(IGraphQLBuilder, Func<HttpContext, TUserContext>)'. There is no implicit reference conversion from 'xyz.Service.GraphQLUserContext' to 'System.Collections.Generic.IDictionary<string, object>'.

While attempting the following code:

        services.AddGraphQL(_ =>
        {
            _.EnableMetrics = true;
            _.ExposeExceptions = true;
        })
        .AddUserContextBuilder(httpContext => new GraphQLUserContext { User = httpContext.User })
        .AddWebSockets(); // Add required services for web socket support;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.