jaf*_*ffa 6 .net c# dependency-injection
我正在为我的项目使用IoC和DI.
但是我想知道以下是否是一个好习惯:
private readonly IMyService myservice;
Run Code Online (Sandbox Code Playgroud)
作为服务使用者的类中的字段.该字段在构造函数中设置.
我确定我已经在某个地方看到了这个,我已经接受了它.不过我也看到了:
private IMyService myservice;
Run Code Online (Sandbox Code Playgroud)
似乎就足够了.是否有任何目的为注入的服务接口提供只读字段?有什么好处?
我认为使用readonly关键字是构造函数注入的正确实现的核心部分.
public class MyClass
{
private readonly IMyService myservice;
public MyClass(IMyService myservice)
{
if (myservice == null)
{
throw new ArgumentNullException("myservice");
}
this.myservice = myservice;
}
}
Run Code Online (Sandbox Code Playgroud)
从readonly技术上讲,关键字和Guard子句都不需要实现构造函数注入.但是,它们都有助于加强班级的不变量.这就是封装的全部内容.
| 归档时间: |
|
| 查看次数: |
1960 次 |
| 最近记录: |