views:

188

answers:

3

Hello!

I'm a huge fan of D.I.
I'm currently developing a not-so-small project which uses D.I. everywhere
(classic and beautiful D.I. by hand).

From my point of view there are following advantages:

  • It's intuitive when you got used to it,
  • doesn't affect readability in negative way (in fact, it gets even better),
  • but the most important thing is: if I want to test parts or whole project with different implementations of some interfaces, I can do it by changing few characters, instead of doing complex refactoring/renaming or other workarounds.

But, sadly, I can't figure out, how D.I. can be used with foreign-created objects in an elegant way (without some frameworks, remember, I do D.I. by hand).

D.I. by hand means: you pass something to a c-tor. No global factories or similar, God forbid!

JAXB, for example, creates objects by itself. There is no way to tell the JAXBContext: "please, use following parameters to create my objects". JAXB only accepts parameterless c-tors.

Any ideas?

A: 

People have been known to use getter injection to do this. I wouldn't know how to do this in a luddite DI environment.

krosenvold
+2  A: 

Doesn't the JAXBContext use a factory method anyway? You can pass parameters into this like you would a constructor. If that doesn't do what you want, traditional setter injection (i.e. calling context.setXyz(xyzInstance) methods) after creating your object would emulate by hand what spring et al do automatically...

grkvlt
+1 I would go with either of the ones suggested. @ivan if you are still not comfortable with the lines of code that would call it, wrap them and move that code elsewhere. Its a restriction and you have to deal with it at some point. I also don't know if java allows, but in .net you can call the constructor of the already instantiated object through reflection.
eglasius
+3  A: 

Why does "D.I. by hand" have to mean "pass something to a c-tor"?

Could you do this?

ThingOne one = new ThingOne();
one.setInjectedItem( a );
one.setOtherInjectedItem( b );

In spring dependency injection, this would be injection via a property and I don't see why this can't be done "by hand."

Alex B