Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL + Autofac

I'm exploring GraphQL at the moment. In one of my ObjectGraphTypes I want to inject a service implementation which queries EF about some addition data.

public class RoomType : ObjectGraphType<Room>
    {
        public RoomType(IUserRepository userRepository)
        {
            Field(x => x.Id).Description("Identifier for a room");
            Field(x => x.Name).Description("Name of the room");
            Field<ListGraphType<UserType>, IEnumerable<User>>().Name("Users").Resolve(ctx =>
            {
                var roomId = ctx.Source.Id;
                return userRepository.GetUsersInRoom(roomId);
            });
        }
    }

Where both RoomType and IUserRepository has been registed within in Autofac container. However, during execution the RoomType cannot be resolved as it's missing a parameterless constructor, which makes me think that its been construction via reflection and not via the container. Any suggestions on how to proceed?

Thanks!

like image 478
Tobias Moe Thorstensen Avatar asked Sep 06 '25 02:09

Tobias Moe Thorstensen


1 Answers

The issue was in the Schema. You have to have an implementation of ISchema which is registered within the container. You also need to register an implementation of IDependencyResolver which is an interface in the GraphQl library (GraphQL.IDependencyResolver) like this:

 builder.Register<IDependencyResolver>(c =>
            {
                var context = c.Resolve<IComponentContext>();
                return new FuncDependencyResolver(type => context.Resolve(type));
            });

At the end, make sure that all of your schemas, queries and types are registered in autofac.

like image 122
Tobias Moe Thorstensen Avatar answered Sep 07 '25 18:09

Tobias Moe Thorstensen