views:

253

answers:

2

While experimenting with this question on collections in Spring.NET, I discovered that Spring can inject a dependency using a private setter. I have two questions:

  1. Is this documented anywhere?
  2. Is using private setters recommended?

The documentation says:

Setter-based DI is realized by calling setter methods on your objects...

Granted, it doesn't explicitly say public setter methods, but that's what I had always assumed. I'm using version 1.0.2 on .NET 3.5.

+2  A: 

Don,

no this is not documented asfaik - mostly because we don't recommend it. The feature is there to support rare cornercases when dealing with legacy/3rd party libraries.

You should only use public setters that you may also call from within your unit tests!

hth, Erich

Erich Eichinger
Thanks! Perhaps it would be worth documenting and explicitly discouraging. Note that adding a private setter actually changes the semantics of collection injection from adding to replacing.
Don Kirkby
+1  A: 

The Java version of Spring uses reflection, which can get at those private setters. That's good, because you wouldn't want to force someone to change an immutable object just to satisfy Spring.

Personally, I prefer using constructor injection whenever I can.

duffymo