How does Spring.NET use private setters?
-
19-08-2019 - |
Question
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:
- Is this documented anywhere?
- 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.
Solution
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
OTHER TIPS
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.