使用构造函数注入,一个依赖被注入到这样的消费者中(至少我希望我理解正确):
public class SomeConsumer
{
private IDependency someDependency;
public SomeConsumer(IDependency someDependency)
{
if (someDependency != null)
{
this.someDependency = someDependency;
}
else
{
throw new ArgumentNullException("someDependency");
}
}
public void Baz()
{
someDependency.DoSomething();
}
(...)
}
如果我要为 IDependency 使用 Null 对象模式,我需要保护子句吗?还是注入 Null 对象是错误的?
更新:为了澄清,假设我有这样的类和接口:
public interface IDependency
{
void DoSomething();
}
public class NullDependency : IDependency
{
public void DoSomething()
{
//Do nothing...
}
}
public class RealDependency : IDependency
{
public void DoSomething()
{
Console.WriteLine("Did something");
}
}
public class Foo
{
public void Bar()
{
IDependency dependency = new NullDependency();
SomeConsumer sc = new SomeConsumer(dependency);
sc.Baz();
}
}
然后我可以安全地从 SomeConsumer 中删除保护子句,使其看起来像:
public class SomeConsumer
{
private IDependency someDependency;
public SomeConsumer(IDependency someDependency)
{
this.someDependency = someDependency;
}
public void Baz()
{
//if someDependency is a NullDependency, this does nothing
someDependency.DoSomething();
}
(...)
}
或者我应该使用保护子句,因为我不能确定它null
永远不会被注入?