Should the dependencies entered be public or private?

Should dependencies be stored in private fields or properties with private setters and public recipients? This applies to the DI constructor.

To be clear, in the example of properties, I did not expect that they would be added to the accompanying interface, if that makes no sense - that is, they will be visible only in the implementation type:

interface IFoo {
  void DoSomething();
}

class Foo : IFoo {
  private readonly IService dependency;
  public Foo(IService dependency) {
    this.dependency = dependency;
  }
}

class Bar : IFoo {
  public Foo(IService dependency) {
    this.Dependency = dependency;
  }

  public IService Dependency { get; private set; }
}
+3
source share
3 answers

private readonly, . " " . , : , .

, , : , . - , . . - (DTO).

: , , ( ).

+10

, .

DI :

  • , : " "
  • , (, , MVVM ..)

, , - . : , , .

TL; DR:. , , - , ctor (s), .

+1

I agree with @Frank that you should keep it secret, this is better for testing, and it gives you the best encapsulation of objects.

Imagine that you need an interface to access only the Bar class, in which case your client can do something Bar.Dependency.BadMethodBurnTheDevice();

0
source

Source: https://habr.com/ru/post/1662992/


All Articles