gpt4 book ai didi

c# - 使用依赖注入(inject) C# 处理 null 的最佳实践

转载 作者:行者123 更新时间:2023-12-02 21:36:11 24 4
gpt4 key购买 nike

如果我有

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

我正在使用 say unity 来解决我的依赖性......

检查 myService 是否为 null 是否是最佳实践?如果是,我应该抛出异常还是创建新的具体实现?

最佳答案

首先,Unity 不会提供null 作为参数值。它要么创建为 IMyService 注册的类型的实例,要么抛出异常:

Exception is: InvalidOperationException - The type IMyService does not have an accessible constructor.


At the time of the exception, the container was:

Resolving Foo.MyController,(none)

Resolving parameter "myService" of constructor Foo.MyController(Foo.IMyService myService) Resolving Foo.IMyService,(none)

因此,不用担心Unity(或其他依赖注入(inject)框架)注入(inject)的null。但是,如果可以手动实例化 Controller ,则有人可能会将 null 传递给构造函数。传递 null 是一种非常难闻的气味——这意味着您的系统出现了问题。因此,最好的选择是检查服务值并抛出 ArgumentNullException:

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

_myService = myService;
}

如果注入(inject)服务应该是可选的。那么我建议你使用属性注入(inject)而不是构造函数注入(inject)

关于c# - 使用依赖注入(inject) C# 处理 null 的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21335867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com