Constructor Injection vs Setter Injection

南笙酒味 提交于 2020-01-26 04:15:27

问题


I have read the following as one of the difference between constructor and setter injection. Can someone explain the below difference with some simple example, I'm bit confused with the term fully function object and incomplete object.

-> Constructor DI allows object to be created in complete state and follows principle of fully functional object while Setter DI allows object to be created without its dependency. which may result in incomplete object if dependency is not available.


回答1:


When using Constructor Injection, all required dependencies should be provided through the constructor, as there should not be any setter, to inject them later on. So the instance has all required dependencies!

With Setter Injection, the create instance might be there, but without all the required dependencies (as they have not been set through the setter). A user can use the object without setting de required dependencies.

See also Dependency injection through constructors or property setters?



来源:https://stackoverflow.com/questions/33361027/constructor-injection-vs-setter-injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!