code_junkie

Inject dependencies in methods or in the constructor?

Nov 11th, 2011
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. //Inject the dependency into the methods that require ImportantClass
  2. Class Something {
  3.  
  4. public Something()
  5. {
  6. //empty
  7. }
  8.  
  9. public void A()
  10. {
  11. //do something without x
  12. }
  13.  
  14. public void B(ImportantClass x)
  15. {
  16. //do something with x
  17. }
  18.  
  19. public void C(ImportantClass x)
  20. {
  21. //do something with x
  22. }
  23. }
  24.  
  25. //Inject the dependency into the constructor once
  26. Class Something {
  27. private ImportantClass _x
  28. public Something(ImportantClass x)
  29. {
  30. this._x = x;
  31. }
  32.  
  33. public void A()
  34. {
  35. //do something without x
  36. }
  37.  
  38. public void B()
  39. {
  40. //do something with this._x
  41. }
  42.  
  43. public void C()
  44. {
  45. //do something with this._x
  46. }
  47.  
  48. }
  49.  
  50. class Foo {
  51. private final Bar _bar;
  52.  
  53. Foo(Bar bar) {
  54. _bar=bar;
  55. }
  56. }
  57.  
  58. public interface IFoo
  59. {
  60. void Do();
  61. }
  62.  
  63. public class IFoo DefaultFoo : IFoo
  64. {
  65. public void Do()
  66. {
  67. }
  68. }
  69.  
  70. public class UsesFoo
  71. {
  72. private IFoo foo;
  73. public IFoo Foo
  74. {
  75. set { this.foo = value; }
  76. }
  77.  
  78. public UsesFoo()
  79. {
  80. this.Foo = new DefaultFoo();
  81. }
  82.  
  83. public UsesFoo( IFoo foo )
  84. {
  85. this.Foo = foo;
  86. }
  87.  
  88. public void DoFoo()
  89. {
  90. this.Foo.Do();
  91. }
  92. }
Add Comment
Please, Sign In to add comment