2

If I have a class HelperClass that I'd like to use within a saga, I'd like to be able to inject an IHelperClass into the constructor.

The problem I'm running into is that sagas appear to be instantiated with an empty constructor; so while I can create a constructor that takes IHelperClass and use it in unit tests, the framework will always call the parameterless constructor.

I think I could use property injection, but since this helper class is "necessary," my understanding is that property injection (assuming it would work) is not a best practice.

So how can I do this without taking a hard dependency on the concrete HelperClass implementation?

ksigmund
  • 527
  • 1
  • 6
  • 13
  • Not sure if this helps, but here goes. What I did in Java (using runtime bytecode manipulation) was to rename the no-arg constructor and change it's method signature to include an extra parameter (your IHelperClass), and inject some code to use it. Then I add a new no-arg constructor as a proxy to the renamed constructor, and inject code using a factory to get an instance of the 'IHelperClass'. That way code that isn't aware of the extra parameter will still work fine. Is something like this feasible? – Kenney Feb 03 '16 at 22:11
  • I'm still coming up to speed on using something other than poor man's DI, so I might be missing something but that generally sounds possible. I think the only thing is that I'd then have to have my class that I'm trying to inject "into" have a dependency on my IoC container. – ksigmund Feb 03 '16 at 22:39
  • I think I've gone about this the wrong way - sorry. You are the one implementing the `Saga` constructors, right? There's no need for runtime byte code manipulation then. In DI, the "necessity" of the helper class is represented by the dependency on the component, being an annotated field, instead of a constructor parameter (that would need a not-null check!). *Property injection* is the exact same idea as constructor parameters. Except that you don't explicitly specify their values in your code, but have a DI engine do it for you - inverting, as it were, control: IoC. – Kenney Feb 03 '16 at 23:40

1 Answers1

3

You don't have to worry about the "necessity" of the help object in the context of the saga since no other code will be instantiating the saga directly.

In short, you can use property injection without concern here.

Udi Dahan
  • 11,932
  • 1
  • 27
  • 35
  • Thanks, Udi! One remaining question for me is wouldn't using property injection require that I remember to specify an implementation of the interface during unit testing? My assumption is that, if I don't, the test will fail as that property will be null. Or is there some way to leverage my IoC container for this as well? – ksigmund Feb 04 '16 at 14:58