Search code examples
rubygraphqlgraphql-ruby

What's the best practice to achieve dependency injection with ruby-graphql?


I want to use dependency injection with graphql-ruby.

I.e.

module CustomerCredits
  module Types
    class QueryType < GraphQL::Schema::Object

      description 'The query root of this schema'

      field :filter_users, [Types::UserType], null: false do
        argument :parameters, InputTypes::UserFilterParameters, required: true
      end

      # resolvers

      def filter_users(arguments) 
        repo = UserRepository.new(complex_arguments) # I want to inject the dependency UserRepository
    
        repo.filtered_users(**arguments[:parameters])
      end

    end
  end
end

Using dependency injection in initialize is not possible, because QueryType is instantiated by graphql-ruby.


Solution

  • As you've mentioned, injection through the initializer might not be super straight forward, so if you want to go fully into dependency injection and inversion of control, you could leverage an IOC Container library like Dry Auto Inject. I know it might be a full blown solution, and it could possibly be too heavy handed for your use case (not sure), but since you're already using repositories in Ruby, it might not be.