c# - Microsoft.Extensions.DependencyInjection 向构造函数注入(inject) null,而不是在服务丢失时抛出异常

标签 c# .net azure dependency-injection azure-functions

使用 3.0 的 Microsoft DI for Azure Functions 的工作效果非常令人惊讶。 如果未找到服务,它会注入(inject) null 而不是抛出异常。它仅发生在子依赖项(而不是根依赖项)中,在下面的情况下,如果 OutboxRelay 构造函数缺少任何参数,DI 会将其解析为 null,而不是抛出服务未注册的异常。

我有以下 Azure Function 3.0:

public class OutboxRelayFunction
{
    private readonly IOutboxRelay _outboxRelay;

    public OutboxRelayFunction(IOutboxRelay outboxRelay)
    {
        _outboxRelay = outboxRelay;
    }

    [FunctionName("OutboxRelay")]
    public async Task Run([TimerTrigger("*/1 * * * * *")]TimerInfo myTimer, ILogger log)
    {
    }
}

我已经使用 Microsoft 的容器配置了 DI:

    using Microsoft.Azure.Functions.Extensions.DependencyInjection;

    [assembly: FunctionsStartup(typeof(Startup))]
    namespace Outbox.Relay
    {
        public class Startup : FunctionsStartup
        {
            public override void Configure(IFunctionsHostBuilder builder)
            {
                 builder.Services.AddScoped<IOutboxRelay, OutboxRelay>();
                 builder.Services.AddSingleton<IBusClient, ServiceBusClient>();
            }
        }
    }

OutboxRelay 构造函数:

public class OutboxRelay : IOutboxRelay
{
    private readonly IOutboxManager _outboxManager;
    private readonly IBusClient _busClient;
    private readonly ILogger<OutboxRelay> _logger;

    public OutboxRelay(IOutboxManager outboxManager,
        IBusClient busClient,
        ILogger<OutboxRelay> logger)
    {
        _outboxManager = outboxManager ?? throw new ArgumentNullException(nameof(outboxManager));
        _busClient = busClient ?? throw new ArgumentNullException(nameof(busClient));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }
}

Debugging

如您所见,在尝试创建 OutboxRelay 实例时,它不会抛出异常,而是简单地将 null 注入(inject)到未在 DI 中注册的 IOutboxManager 中。我可以更改默认行为,以便在尝试解析 OutboxRelay 实例时引发异常吗?

最佳答案

我认为这不可能。

由于IOutboxManager引用类型,因此可以定义类似IOutboxManager outboxManager = null的内容。然后在构造函数public OutboxRelay(IOutboxManager outboxManager,xxx)中,无论IOutboxManager是什么,给参数outboxManager传递null就可以了 是否在 DI 中注册。你应该总是使用 ??运算符来确定是否抛出错误。

关于c# - Microsoft.Extensions.DependencyInjection 向构造函数注入(inject) null,而不是在服务丢失时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60379123/

相关文章:

asp.net - 在 azure blob 存储中生成 ZIP 文件

c# - 如何在 WPF 中为图像缩放变化设置动画?

c# - Graphics.DrawString 指定文本的不透明度

c# - 使用 c++/cli 和在 c# 中使用它的事件处理

c# - Ajax.BeginForm 似乎重定向 Action 完成

.net - 如何使用 SevenZipSharp 创建压缩的 SFX 文件?

c# - WSDL 应该如何构建?

c# - 为什么返回 List<T> 的方法不能实现返回 IEnumerable<T> 的方法?

azure - Azure 数据库时间是如何计算的?

azure - 是否可以使用 Azure 数据工厂中的数据流修改(插入/更新)本地 SQL 服务器