Hotchocolate: How to resolve service registered in IServiceCollection?

Created on 29 Nov 2018  ยท  15Comments  ยท  Source: ChilliCream/hotchocolate

When using ASP.NET Core and registering services in IServiceCollection from Startup.ConfigureServices method, those services then are not available in IResolverContext when I use T Service<T>().

Is this by design or a bug?

โ“ question

All 15 comments

Are you using our middleware?

I'm trying to resolve service from context of IMiddlewareContext. My middleware is registered with IMiddlewareConfiguration.Use(FieldMiddleware middleware). I have not registered any service provider on schema configuration. GraphQL is added from GraphQLApplicationBuilderExtensions.

let me do a quick test with the middleware context ....

It works with preview.3

I have added this to the posted startup.cs

c.Use(next => context =>
                {
                    if (context.Service<CharacterRepository>() == null)
                    {
                        throw new NotSupportedException();
                    }
                    return next(context);
                });

Can you give feedback once you figured it out so I can close this issue or we can investigate further.

I made upgrade to 0.7.0-preview.3 and still getting the same issue. Can it be related to the fact that I'm using schema first approach? It looks like my setup is the same as in https://github.com/ChilliCream/hotchocolate-aspnetcore/blob/next/examples/StarWars/Startup.cs

Should not make a difference.... can you share some code?

We could create a small StarWars schema first project...

Could you set up a small schema first project that replicates and share that repo?

Could you set up a small schema first project that replicates and share that repo?

Working on it

On fresh project it works as expected. I will add more code to it in order to replicate setup.

The issue actually arrises when services are registered in same action that configures schema. When they are registered before or after AddGraphQL is called, then it works fine.

Fore example, this would not work

services.AddGraphQL(sp => Schema.Create(@"
    type Mutation {
        authenticate(email: String!, password: String!): String
    }
", c => {
    services.AddSingleton<IMySvc, MySvc>();
    c.BindType<Mutation>();
    c.Use(next => ctx => {
        if (ctx.Service<IMySvc>() == null) {
            throw new System.NotSupportedException();
        }
        return next(ctx);
    });
}));

Adding services within the schema configure action is not supported since when this action is called the IServiceProvider instance is already created and cannot be modified.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

marcin-janiak picture marcin-janiak  ยท  4Comments

tunurgitr picture tunurgitr  ยท  4Comments

sfmskywalker picture sfmskywalker  ยท  3Comments

sgt picture sgt  ยท  4Comments

benmccallum picture benmccallum  ยท  5Comments