#.net-core #dependency-injection #graphql
#.net-core #внедрение зависимостей #graphql
Вопрос:
Я следую примеру на https://github.com/graphql-dotnet/server чтобы создать GraphQL, но я получаю вышеуказанную ошибку (полная версия ниже) при переходе к моему http://localhost:5001/graphql .
Я поиграл со многими аспектами asp.core DependencyInjections, но все равно возвращается к этой ошибке:
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.<GetCallSite>b__0(Type type)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 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.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 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)
Может кто-нибудь указать мне правильное направление, чтобы исправить это, пожалуйста
.Net Core 5.0;
Последняя версия Nuget GraphQL.Net Сервер
Мой код Startup.cs
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();
}
}
}
Мой файл схемы
public class MySchema : Schema,ISchema
{
public MySchema(IServiceProvider provider):base(provider)
{
{
Query = provider.GetRequiredService<MyQuery>();
}
}
}
И мой запрос
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);
}}}
Ответ №1:
https://github.com/graphql-dotnet/server/issues/454
Проблема заключалась в том, что я пытался создать службу для этого типа, и я должен был просто создать ее для своего класса I.E
services.AddSingleton<ISchema, MySchema>();
изменено на
services.AddSingleton<MySchema>();