在 Azure 函数中缺少注册时依赖注入注入 null

Zen*_*uka 8 c# dependency-injection azure-functions

我被null注入到我的构造函数中,该构造函数具有我忘记注册的依赖项。

在下面的示例中,null当您忘记IDepencency在启动类中注册时,依赖项

public class AzureFunction {
    public AzureFunction(IDepencency dependency) {

    }
}
Run Code Online (Sandbox Code Playgroud)

我希望它可以像在 .net core DI 中一样工作。

这是预期的行为吗?我可以更改设置以启用抛出异常吗?

编辑:

阅读 HariHaran 的回答后,我意识到它只发生在子依赖项中。这是一个可重现的示例:

public interface IClass1 { }

public class Class1 : IClass1
{
    private readonly IClass2 _class2;

    public Class1(IClass2 class2)
    {
        _class2 = class2; // This will be null
    }
}

public interface IClass2 { }

public class Class2 : IClass2 { }

public class Function1
{
    private readonly IClass1 _class1;
    public Function1(IClass1 class1)
    {
        _class1 = class1;
    }

    [FunctionName("Function1")]
    public async Task<HttpResponseMessage> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous,"post", Route = null)]
        HttpRequestMessage req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");
        return req.CreateResponse(HttpStatusCode.Accepted);

    }
}
Run Code Online (Sandbox Code Playgroud)

并将其放入functionsStartup

[assembly: FunctionsStartup(typeof(Startup))]
namespace FunctionApp2
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddSingleton<IClass1, Class1>();
            //builder.Services.AddSingleton<IClass2, Class2>(); // Leave this commented
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

Pha*_*ynh 1

如果框架没有抛出异常,那么您可以在函数的构造函数中手动执行此操作。

例如

public class AzureFunction {
    private readonly IDependency _dependency;

    public AzureFunction(IDepencency dependency) {
        _dependency = dependency ?? throw new ArgumentNullException(nameof(dependency));
    }

    //...
}
Run Code Online (Sandbox Code Playgroud)