dry-rb / dry-auto_inject

Container-agnostic constructor injection mixin

Home Page:https://dry-rb.org/gems/dry-auto_inject/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

New DI strategies

wojtha opened this issue · comments

I've played with Dry::AutoInject in Rails. But as you know, one of biggest pain points in Rails is zero control over controllers initialization which makes Dry::AutoInject unusable here. So I started to play with other DI strategies last night. And this is the result...

I've created three additional strategies:

  1. Dry::KeyInject constructor DI using keyword arguments
  2. Dry::SetterInject setter DI; allows to set visibility of readers
  3. Dry::GetterInject not real DI (maybe container injection is the right term?), adding only readers to container settings which can be stubbed when needed; allows to set visibility of readers

The code lives as gist for now here: https://gist.github.com/wojtha/b9730d108625e04a0642

Example of using Dry::GetterInject in Rails controllers and using Rails.configuration as DI container: https://gist.github.com/wojtha/322ddfe6323b647e4fc3

@solnic what do you think? should I start PR or a new gem?

Please open a PR for k/w arg based constructor (would be awesome if it falls back to hash for rubies w/o kwargs).

The rest needs some discussion. I'm definitely going to be against setters though. Introducing an interface just because of testing conveniences would be a smell.

Oh one more thing - we have dry-constructor now. Maybe it could be used here

@wojtha There is a thread at dryrb/dry-constructor#1related to the different constructors.

@wojtha I have just successfully ported a Rails job over to using the dry-container / auto_inject, and now looking to understand how I can use this more extensively, did you decide on a best approach?

E.g. where do you register the objects? and did the Getter strategy work out well for use in the controllers?

@DangerDawson @timriley has been working on using AutoInject with existing constructors lately, it should work now in theory

@DangerDawson sorry wasn't able to get back to this one in last few months, but I keep it on my radar. I haven't time to look on dry-constructors yet 😞

Right now I think the best approach for dry-auto_inject is to focus on constructor injection. We do have support for supplying extra/alternative injection strategies when setting up the injector, though, so this might be a good avenue for pursuing your setter injection strategy. You can see an example of this over here in trailblazer: trailblazer/trailblazer@7e11f95

As for your "key inject" strategy, well, that is now the default! 😄

I'll close this for now, but if you have any other thoughts, happy to talk things over.