是否有必要使用构造函数注入检查空值? [英] Is it necessary to check null values with constructor injection?

查看:29
本文介绍了是否有必要使用构造函数注入检查空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 .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.

  • 这段代码是在公共库中,被多人使用还是实际上没有遵循依赖注入?

那就去做吧.手动实例化会在某处导致 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.

更好的是,正如@ScottFraley 所提到的,使用较新的 C# 版本,以上内容的可读性更高:

Even better, as @ScottFraley mentions, with newer C# versions, the above can be even more readable:

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

这篇关于是否有必要使用构造函数注入检查空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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