是否有必要使用构造函数注入检查空值? [英] Is it necessary to check null values with constructor injection?
问题描述
我正在使用.NET Core构造函数注入。
在一位同事的代码审查中,他提出了一个问题,即我是否应该检查控制器中注入的依赖项的空值。
I'm using .NET Core constructor injection. In a code review from a colleague, he raised the question if I should check for null values on injected dependencies in controllers.
由于该框架负责创建服务的实例,在我看来,它将处理所有错误,并且永远不会将空值依赖项传递给构造函数。但是我没有任何事实证据,因此我想知道是否有必要进行空检查。
Since the framework is responsible for creating an instance of the service, it seems to me that it would take care of any errors and never have a null value dependency passed to a constructor. I don't have any factual evidence for this though, so I'd like to know if it's possible that a null check may be necessary.
例如,我是否应该检查以下代码中的 myService是否为空? (假设代码配置为使用DI)
For example, should I check if 'myService' is null in the following code? (Assuming the code is configured to use DI)
public class MyController
{
private readonly IMyService _myService;
public MyController(IMyService myService)
{
_myService = myService;
}
}
推荐答案
是否需要使用构造函数注入检查空值?
Is it necessary to check null values with constructor injection?
这取决于。
- 您和(可能)某些队友在(很幸运)代码审查环境中使用的此内部代码吗?
不要。这不是必需的。该框架不允许这样做。
Don't. It's not necessary. The framework doesn't allow this.
- 此代码是公共库中的,供多人使用还是在依赖注入之后没有实际使用? / li>
- Is this code in a public library, used by multiple people or not actually following Dependency Injection?
然后执行此操作。手动实例化会在某个地方导致NullReferenceException,并且很难找到它们。
Then do it. A manual instantation would result in a NullReferenceException somewhere and those are hard to track down.
也就是说,使用类似这样的东西:
That said, using something like this:
public MyController(IMyService myService)
{
if (myService == null)
{
throw new ArgumentNullException(nameof(myService));
}
_myService = myService;
}
这是一张非常便宜的支票,如果有人通过 null
由于某些原因。
Is an extremely cheap check and it's much easier to track down if someone passes null
for some reason.
这篇关于是否有必要使用构造函数注入检查空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!