注入的依赖关系是否可以公开访问或私有? [英] Should injected dependencies be publicly accessible or private?

查看:145
本文介绍了注入的依赖关系是否可以公开访问或私有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否将依赖关系存储到具有私有setter和public getter的私有域或属性中?这就适用于构造函数DI。

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

为了清楚,在属性示例中,我不希望将这些添加到附带的界面中,除非有意义 - 即他们会仅在实现类型中可见:

To be clear, in the property example, I would not expect these to be added to an accompanying interface unless it made sense - i.e. they would only be visible 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; }
}


推荐答案

code> private readonly 字段,只要不需要从对象外部访问依赖关系即可。将您的对象视为黑盒子,并尽可能少地在其公共界面中。这种做法被称为 封装原则 信息隐藏,也适用于注入的依赖关系:暴露的越少,您减少班级和班级用户之间紧密耦合的程度越多。

I would always recommend private readonly fields, as long as there is no need to access the dependency from outside of the object. Treat your objects as "black boxes" and put as little as possible in their public interfaces. This practice is better known as encapsulation principle or information hiding and also applies to injected dependencies: The less you expose, the more you reduce tight coupling between your class and your class' users.

另外一个应该提到的原则是建模对象的行为:告诉,不要问。如果您需要完成任务,请询问对象为您做。它将在该过程中使用它的依赖关系。要求属性和自己做的工作只应该是数据对象(DTO)的首选。

Another principle that should be mentioned is modeling the behavior of objects: Tell, don't ask. If you need to get something done, ask the object to do it for you. It will use its dependencies in the process. Asking for properties and doing the work yourself should only be the first choice for data objects (DTOs).

这也是首先使用构造函数注入的原因:每个人都会做属性注入,如果暴露依赖关系作为属性是最佳实践,因为这意味着更少的代码(我们不需要构造函数)。

This is also the reason for using constructor injection in the first place: Everybody would be doing property injection instead, if exposing dependencies as properties was best practice, as this would mean less code (we wouldn't need the constructors then).

这篇关于注入的依赖关系是否可以公开访问或私有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆