Injection through constructor (not using include...)


#1

Hi, everyone

I’m coming from .Net “world” and I’m having a hard time finding dependency injection information with Ruby.

Recently, I’ve discovered Dry Container and started studying it. So I got to the point where I’d like to design my classes simply using constructor injection:

class SomeClass
def initialize(some_repository)
@some_repository = some_repository
end
end

And the container should be able to resolve the dependencies. Is it possible?


#2

dry-auto_inject uses constructor injection, it literally defines a constructor for you.


#3

The How does it work? page from the docs might also help clarify how it works :slight_smile:


#4

Got it!

I don’t like the idea of forcing my classes to include that constant. I think this pollutes the classes and may force changes to all of them if I change the container in the future (for some other that uses a different injection strategy).

I wish I could use constructor injection (coded by me) and let the container create all the object graph from the application entry point (concept named Composition Root/Agent). The container would be responsible to create the first object required (the web controller, for instance) and all dependencies, but I don’t know if it’s possible to intercept this creation in Ruby frameworks. I couldn’t find anything like that in any Ruby applications.

Sorry if I didn’t make myself clear (feel free to ask). I’ll keep studying Ruby and searching more content about DI in Ruby.

Thanks!