.net-coredependency-injectiongraphql

Unable to resolve service for type 'xxxSchema' while attempting to activate 'GraphQL.Server.Internal.DefaultGraphQLExecuter


I am following the sample on https://github.com/graphql-dotnet/server to create a GraphQL but I am getting the above error (Full version Below) when going to my http://localhost:5001/graphql.

I have played around with many aspects of ASP.NET Core dependency injection but I still get this error:

System.InvalidOperationException: Unable to resolve service for type 'MyProject.GraphQL.MySchema' while attempting to activate 'GraphQL.Server.Internal.DefaultGraphQLExecuter`1[MyProject.GraphQL.MySchema]'.

at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateOpenGeneric(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot, Boolean throwOnConstraintViolation)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateOpenGeneric(Type serviceType, CallSiteChain callSiteChain)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.<>c__DisplayClass7_0.b__0(Type type)
at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(Type serviceType, CallSiteChain callSiteChain)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.CreateServiceAccessor(Type serviceType)
at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at GraphQL.Server.Transports.AspNetCore.GraphQLHttpMiddleware`1.InvokeAsync(HttpContext context) in /_/src/Transports.AspNetCore/GraphQLHttpMiddleware.cs:line 136 at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Can anyone point me to the right direction to fix this please?

ASP.NET Core 5.0 with the latest Nuget GraphQL.Net server.

My Startup.cs code is:

using GraphQL;
using GraphQL.Server;
using GraphQL.SystemTextJson;
using GraphQL.Types;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;

namespace Ace.Aceterilize
{
    public class Startup
    {
        public Startup(IConfiguration configuration, IWebHostEnvironment environment)
        {
            Configuration = configuration;
            Environment = environment;
        }

        public IConfiguration Configuration { get; }

        public IWebHostEnvironment Environment { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Singleton);

            services.AddHttpContextAccessor();
            //GraphQL
            services.AddSingleton<IDocumentExecuter, DocumentExecuter>();
            services.AddSingleton<IDocumentWriter, DocumentWriter>();

            services.AddSingleton<MyQuery>();
            services.AddSingleton<ISchema, MySchema>();

            services.AddGraphQL((options, provider) =>
                {
                    options.EnableMetrics = Environment.IsDevelopment();
                    var logger = provider.GetRequiredService<ILogger>();
                    options.UnhandledExceptionDelegate = ctx => logger.Error("GraphQL: {Error} occurred", ctx.OriginalException.Message);
                })

            // Add required services for GraphQL request/response de/serialization
           .AddSystemTextJson(configureDeserializerSettings => { }, configureSerializerSettings => { })
           .AddErrorInfoProvider(opt => opt.ExposeExceptionStackTrace = Environment.IsDevelopment())
           .AddWebSockets() // Add required services for web socket support
           .AddDataLoader() // Add required services for DataLoader support
           .AddGraphTypes(typeof(AceteriliseSchema), ServiceLifetime.Transient);

        services.AddControllersWithViews();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            //... Standard if development Mode
        }

        app.UseWebSockets();

        app.UseGraphQL<MySchema, GraphQLHttpMiddlewareWithLogs<MySchema>>();
        app.UseGraphQLWebSockets<MySchema>();

        // use graphiQL middleware at default path /ui/graphiql
        app.UseGraphiQLServer();

        // use graphql-playground middleware at default path /ui/playground
        app.UseGraphQLPlayground();

        // use altair middleware at default path /ui/altair
        app.UseGraphQLAltair();

        // use voyager middleware at default path /ui/voyager
        app.UseGraphQLVoyager();
    }
}

My schema file:

public class MySchema : Schema,ISchema
{
        public MySchema(IServiceProvider provider):base(provider)
        {
            Query = provider.GetRequiredService<MyQuery>();
        }
}

And my query:

 public class MyQuery : ObjectGraphType
 {
        public MyQuery(MyDbContext db)
        {
            Field<ListGraphType<ApplicationUserType>>("users", "List of Active Users",
                  
                resolve: context => db.ApplicationUsers.Where(u => !u.IsDeleted));
        }
 }

 public class ApplicationUserType : ObjectGraphType<ApplicationUser>
 {
        public ApplicationUserType()
        {
            Field(t => t.Id);
            Field(t => t.UserName);
        }
 }

Solution

  • https://github.com/graphql-dotnet/server/issues/454

    The issue was I was trying to create a service for the type, And I should have just created it for my class I.E

    services.AddSingleton<ISchema, MySchema>();
    

    changed to

    services.AddSingleton<MySchema>();