Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/66045463/whats-the-best-practice-to-achieve-dependency-injection-with-ruby-graphql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...