c# - 是否有必要使用构造函数注入(inject)检查空值?

标签 c# dependency-injection .net-core constructor-injection null-check

我正在使用 .NET Core 构造函数注入(inject)。 在一位同事的代码审查中,他提出了一个问题,即我是否应该检查 Controller 中注入(inject)依赖项的空值。

由于框架负责创建服务的实例,在我看来它会处理任何错误并且永远不会将空值依赖项传递给构造函数。不过我对此没有任何事实证据,所以我想知道是否有必要进行空检查。

例如,我是否应该检查以下代码中的“myService”是否为空? (假设代码配置为使用 DI)

public class MyController
{
    private readonly IMyService _myService;

    public MyController(IMyService myService) 
    {
        _myService = myService;
    }
}

最佳答案

Is it necessary to check null values with constructor injection?

视情况而定。

  • 这个内部代码是否由您和(可能)一些队友在(幸运的)代码审查环境中使用?

不要。这不是必需的。该框架不允许这样做。

  • 此代码是否在公共(public)库中,由多人使用或实际上没有遵循依赖注入(inject)?

那就去做吧。手动实例化会在某处导致 NullReferenceException,而这些很难追踪。

也就是说,使用这样的东西:

public MyController(IMyService myService) 
{
    if (myService == null)
    {
        throw new ArgumentNullException(nameof(myService));
    }

    _myService = myService;
}

是一种非常便宜的检查,如果有人出于某种原因通过了 null,则更容易追踪。


更好的是,正如@ScottFraley 提到的,使用更新的 C# 版本,上面的代码可读性更强:

public MyController(IMyService myService) 
{
    _myService = myService ?? throw new ArgumentNullException(nameof(myService));
}

关于c# - 是否有必要使用构造函数注入(inject)检查空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52880470/

相关文章:

c# - 在linq中找到两个列表的交集?

silverlight - 有没有办法判断某些代码是否在 Silverlight 单元测试框架内执行?

c# - 尽管模型有效,但 TryValidateModel 仍返回 false

c# - 未能创建 CoreCLR,HRESULT : 0x80070057

c# - 从 OpenFileDialog 处理多个选定的文件

c# - 找不到如何使用 HttpContent

c++ - C++ 中构造函数注入(inject)的高级配置

.net - dotnet 测试 : how to include assembly name into the . trx 结果文件?

c# - 显示和隐藏 winforms 的部分内容(扩展?)C# .NET

php - 依赖注入(inject)和工作单元模式