Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Obsolete in services.AddGraphQL #2856

Closed
apis3445 opened this issue Jan 13, 2022 · 25 comments
Closed

Obsolete in services.AddGraphQL #2856

apis3445 opened this issue Jan 13, 2022 · 25 comments
Labels
question Developer asks to help him deal with some problem

Comments

@apis3445
Copy link

Summary

Hello! I am using version 4.7.1 in .net & and now Visual studio shows a warning that services.AddGraphQL is obsolete, but I couldn't find any documentation about the new method. I added the GraphQL.MicrosoftDI but I don't know how to use

@sungam3r
Copy link
Member

https://github.com/graphql-dotnet/graphql-dotnet/blob/master/src/GraphQL.Harness/Startup.cs:

using GraphQL.MicrosoftDI;

 public void ConfigureServices(IServiceCollection services)
        {
            // add execution components
            services.AddGraphQL(builder => builder
                .AddSystemTextJson()
                .AddErrorInfoProvider((opts, serviceProvider) =>
                {
                    var settings = serviceProvider.GetRequiredService<IOptions<GraphQLSettings>>();
                    opts.ExposeExceptionStackTrace = settings.Value.ExposeExceptions;
                })
                .AddSchema<StarWarsSchema>()
                .AddGraphTypes(typeof(StarWarsQuery).Assembly)
                .AddMiddleware<CountFieldMiddleware>(false) // do not auto-install middleware
                .AddMiddleware<InstrumentFieldsMiddleware>(false) // do not auto-install middleware
                .ConfigureSchema((schema, serviceProvider) =>
                {
                    // install middleware only when the custom EnableMetrics option is set
                    var settings = serviceProvider.GetRequiredService<IOptions<GraphQLSettings>>();
                    if (settings.Value.EnableMetrics)
                    {
                        var middlewares = serviceProvider.GetRequiredService<IEnumerable<IFieldMiddleware>>();
                        foreach (var middleware in middlewares)
                            schema.FieldMiddleware.Use(middleware);
                    }
                }));

@sungam3r sungam3r added needs confirmation The problem is most likely resolved and requires verification by the author question Developer asks to help him deal with some problem labels Jan 13, 2022
@fubar-coder
Copy link

fubar-coder commented Jan 13, 2022

The source you've shown is from the develop branch, but the 4.7.1 release doesn't contain an AddGraphQL extension method that takes an Action<IGraphQLBuilder>.

We don't have a way to use comfortably use the new API in GraphQL.MicrosoftDI, because (at least in ASP.NET Core 6.0), the global namespaces will always include Microsoft.Extensions.DependencyInjection.

@sungam3r
Copy link
Member

@Shane32
Copy link
Member

Shane32 commented Jan 13, 2022

@apis3445 There are now two different IGraphQLBuilder interfaces. The obsolete one from the server project and the new one in the main project. The old one will be supported for the remainder of the 4.x lifetime but it is being replaced by the new one. There is also two extension methods called AddGraphQL - the new one in GraphQL.MicrosoftDI and the old one in the server project. The new one uses the new interface of course.

Please note that there are subtle differences in functionality; it is advised to read the documentation for the new builder methods and be sure they fit your needs.

https://graphql-dotnet.github.io/docs/getting-started/dependency-injection#dependency-injection-registration-helpers

@Shane32
Copy link
Member

Shane32 commented Jan 13, 2022

We don't have a way to use comfortably use the new API in GraphQL.MicrosoftDI, because (at least in ASP.NET Core 6.0), the global namespaces will always include Microsoft.Extensions.DependencyInjection.

Known issue - you will need to reference the extension method explicitly as a simple static method rather than using it as an extension method. After the old extension methods are removed in the next major version, this will not be an issue.

We thought it best to mark the old methods as obsolete so everyone had time to transition to the new methods, reducing the difficulty switching to the next major version.

@Shane32
Copy link
Member

Shane32 commented Jan 13, 2022

I suggest reviewing the current (master branch) sample Startup.cs file in the server project, since that's where you are running into the issue.

https://github.com/graphql-dotnet/server/blob/master/samples/Samples.Server/Startup.cs

@apis3445
Copy link
Author

Sorry I can't get the project working.
If I added the codemGraphQL.MicrosoftDI.GraphQLBuilderExtensions.AddGraphQL(services) I got the error

: Error CS0234: The type or namespace name 'MicrosoftDI' does not exist in the namespace 'CaducaRest.GraphQL' (are you missing an assembly reference?) (CS0234) (CaducaRest)

If I added the code in the link
services.AddSingleton<ISchema, CaducidadSchema>(services => new CaducidadSchema(new SelfActivatingServiceProvider(services)));

I got error
Unable to resolve service for type 'GraphQL.Server.Transports.AspNetCore.IGraphQLRequestDeserializer' while attempting to activate 'GraphQL.Server.Transports.AspNetCore.GraphQLHttpMiddleware`1[GraphQL.Types.ISchema]'.

My repo is https://github.com/apis3445/CaducaRest

@sungam3r
Copy link
Member

sungam3r commented Feb 4, 2022

@apis3445 I cloned your repo and it compiles. I see that you commented GraphQL.NET code and use HotChocolate. If this issue is no actual anymore for you then please close.

@apis3445
Copy link
Author

apis3445 commented Feb 5, 2022

Because I didn't have any response I change and comment the code, but the issue still exists if you comment hotchcolate and uncomment grapqhl

@sungam3r
Copy link
Member

sungam3r commented Feb 5, 2022

I don't know what to comment/uncomment exactly. Please provide ready-to-go example.

@apis3445
Copy link
Author

apis3445 commented Feb 5, 2022

You can use this version https://github.com/apis3445/CaducaRest/tree/c61f04f26f9ff95f13f55cafca01499fd0631ff9/CaducaRest and update code to don't mark obsolete

@sungam3r
Copy link
Member

sungam3r commented Feb 5, 2022

            services.AddSingleton<ISchema,CaducidadSchema>();
            services.AddSingleton<CaducidadInputType>();
            services.AddSingleton<CaducidadMutation>();

            // problem code here
            var builder = GraphQLBuilderExtensions
                .AddGraphQL(services)
                .AddServer(true, (options, provider) =>
                {
                    options.EnableMetrics = CurrentEnvironment.IsDevelopment();
                    var logger = provider.GetRequiredService<ILogger<Startup>>();
                    options.UnhandledExceptionDelegate = ctx => logger.LogError("{Error} occured", ctx.OriginalException.Message);
                });
            global::GraphQL.GraphQLBuilderExtensions.AddErrorInfoProvider(builder, opt => opt.ExposeExceptionStackTrace = CurrentEnvironment.IsDevelopment());
            global::GraphQL.SystemTextJson.GraphQLBuilderExtensions.AddSystemTextJson(builder); // For .NET Core 3+
            global::GraphQL.DataLoader.GraphQLBuilderExtensions.AddDataLoader(builder); // Add required services for DataLoader support
            global::GraphQL.GraphQLBuilderExtensions.AddGraphTypes(builder, typeof(CaducidadSchema).Assembly); // Add all IGraphType implementors in assembly which ChatSchema exists
            // end

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient<IAuthorizationHandler, PermisoEditHandler>();

@Shane32 It was not worth marking methods as obsolete. Very few people will understand what to change to get rid of warning.
@apis3445 We already removed all that "old stuff" and consolidated extension methods to work well but these changes is from develop branch. We plan to release in April.

@apis3445
Copy link
Author

apis3445 commented Feb 7, 2022

I Agree if you don't provide a way to remove obsolete with the current version is better don't add the obsolete until you have the correct guides and correct version to use the new methods. It's not easy understand how to clear the obsolete warnings

@sungam3r
Copy link
Member

sungam3r commented Feb 7, 2022

@apis3445 Now only two developers support GraphQL.NET - @Shane32 and I. I prefer to get rid of the old code immediately, even if the price of backward incompatibility. @Shane32 is more careful and prefers to mark old code as Obsolete to give clients time to upgrade. It so happened that in this case the final result is far from the ideal. Sorry.

@Shane32
Copy link
Member

Shane32 commented Feb 7, 2022

@sungam3r It is easy to release another version of the server project without the obsolete methods, that is compatible with GraphQL.NET 4.x. It is not the main project that caused the methods to be obsolete. And supporting two different builders within the server project certainly is confusing. I actually didn't even merge in those changes for about 5 months (from mid July until your review in late December), precisely because of the confusion it would cause having two sets of builder methods in one repo.

@Shane32
Copy link
Member

Shane32 commented Feb 7, 2022

Would you want to do this @sungam3r? I'm sure I could pretty easily; but what should the version number be? 6?

@sungam3r
Copy link
Member

sungam3r commented Feb 7, 2022

I would not release v6. Only two months left to the planned release in April. Only extra work.

@sungam3r
Copy link
Member

@apis3445 Do you have any questions left?

@apis3445
Copy link
Author

No I only prefer if you add something to obsolete add a sample about how to remove in the same version

@sungam3r sungam3r removed the needs confirmation The problem is most likely resolved and requires verification by the author label Feb 14, 2022
@Navusas
Copy link

Navusas commented Apr 29, 2022

I thought it's just me who is struggling for 2 days now trying to get it setup on a completely new project...

Was hoping setting up GraphQL on a new project is going to be < 20 minute job, but it turned out to be mission impossible.

@Shane32
Copy link
Member

Shane32 commented Apr 29, 2022

@Navusas I'm sorry to hear you've had so many difficulties; it should be easy. For the moment, I will post a fully working copy of a GraphQL server for you.

Project file

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="GraphQL.AspNetCore3" Version="2.1.0" />
    <PackageReference Include="GraphQL.SystemTextJson" Version="5.1.1" />
  </ItemGroup>

</Project>

Program.cs file

using GraphQL;
using GraphQL.MicrosoftDI;
using GraphQL.SystemTextJson;
using GraphQL.AspNetCore3;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGraphQL(b => b
    .AddAutoSchema<Query>()  // schema
    .AddSystemTextJson());   // serializer

var app = builder.Build();
app.UseDeveloperExceptionPage();
app.UseWebSockets();
app.UseGraphQL("/graphql");  // url to host GraphQL endpoint
await app.RunAsync();

Schema

public class Query
{
    public static string Hero() => "Luke Skywalker";
}

Sample request url

http://localhost:5000/graphql?query={hero}

Sample response

{"data":{"hero":"Luke Skywalker"}}

More info

As for the data loader, just reference GraphQL.DataLoader version 5.1.1 and add the using, then include .AddDataLoader() within the GraphQL builder code. I wrote the majority of the dataloader code, so let me know if you have any questions.

builder.Services.AddGraphQL(b => b
    .AddAutoSchema<Query>()
    .AddDataLoader()     // <----  (no particular location within this block)
    .AddSystemTextJson());

I suggest reading this page which has examples for setting up Playground/GraphiQL, adding authentication, response compression, configuring CORS, and so on.

I would also suggest reading this page, which has a list of all of the different builder methods available:

Eventually we hope to merge all of the code within GraphQL.AspNetCore3 back into the GraphQL.Server project, but it will probably take another month or two before that is accomplished. In the meantime, you can review what documentation there is on the older GraphQL.Server project here: (which isn't a whole lot)

As for writing the actual graphs, you can read the main website documentation here:

There's not much on the new "type-first" schema syntax yet, unfortunately, but it should be pretty well documented for "code-first" and "schema-first" syntaxes. If you're interested in "type-first" graphs, such as demonstrated above, I would read the "new features" portion of the v5 migration guide, where I added a number of samples and described the new functionality.

You can find working example projects at all of these locations:

@Navusas
Copy link

Navusas commented May 3, 2022

Thanks for all the resources @Shane32 👍
Your example worked in a matter of minutes, but I needed a bit more complex solution (i.e. EF core database, services injection, etc).

I went through quite a few of them and wasn't able to get the project going to be honest. Most of them uses the v4 graphql-dotnet, which seems to somewhat work differently from v5.

I went through the public docs many times, but must admit that I would just skim through them in a few seconds, don't find anything, and then come back to the tutorials you have listed above. (It's just in my nature, I guess, that I don't read every single line/sentence in the docs, I am more of "oh, this looks cool, let's try it".

But anyways, after about 3-4 days of going through tutorials and trying to set it the basic app, I have finally decided to sit down, spend a few hours on docs and read most of the stuff in it, leaving some notes while I do that. Must admit that after I did it was much easier to create the project from scratch (I guess I took an hour to make the project below). I found that some of the most useful information for me personally was hidden usually either in the middle or right at the end.

So, note to myself. Read more docs! 📝

For anyone else as lost as I was, here is the most basic solution (not perfect) of getting GraphQL-dotnet v5 working with .NET 6 (using EF Core code-first approach).
https://github.com/Navusas/graphql5-dotnet6

@SpicyCatGames
Copy link

In graphql version 7.8.0, @Shane32 's answer gives error "The type 'IGraphQLBuilder' is defined in an assembly that is not referenced. You must add a reference to assembly 'GraphQL, Version=4.6.1.0" with the AddGraphQL() also marked as obsolete. So We are forced not to use new version? I cannot find what the correct way to do it is in new version.

@Shane32
Copy link
Member

Shane32 commented Apr 11, 2024

@SpicyCatGames Please provide a list of your GraphQL nuget packages you are referencing along with their version numbers.

@Shane32
Copy link
Member

Shane32 commented Apr 12, 2024

Without knowing what NuGet packages you have installed, it's hard to say, but generally I expect that you still have a reference to an old GraphQL.NET Server package. So long as you have v7 GraphQL.NET Server packages installed, you should be able to use v7 GraphQL.NET packages. Please note that some old packages are not necessary and should be removed for proper operation. Please see the readme file at https://github.com/graphql-dotnet/server for a list of packages which should be removed when upgrading to v7.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Developer asks to help him deal with some problem
Projects
None yet
Development

No branches or pull requests

6 participants