依赖项注入在Azure函数中缺少注册时注入null [英] Dependency injection injecting null when missing registration in Azure functions
问题描述
我正在将null
注入我的构造函数中,该构造函数具有我忘记注册的依赖项.
I'm getting null
injected into my constructor that has a dependency which I forgot to register.
在下面的示例中,当您忘记在启动类中注册IDepencency
时,依赖关系将为null
In the below example dependency would be null
when you forget to register IDepencency
in the startup class
public class AzureFunction {
public AzureFunction(IDepencency dependency) {
}
}
我希望它的工作方式与.net core DI中的工作相同.
I expected it to work the same as in .net core DI.
这是预期的行为吗?我是否可以更改设置以启用抛出异常?
Is this expected behavior? And can I maybe change a setting to enable throwing exceptions?
在阅读了HariHaran的答案之后,我意识到这只是在子依赖中发生.这是一个可重现的示例:
After reading HariHaran's answer, I realized it's only happening in a sub-dependency. This is a reproducible example:
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);
}
}
并将其放在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
}
}
}
推荐答案
不,这不是预期的行为.默认情况下,func host
会抛出
No this is not the expected behaviour. The func host
by default will throw
在尝试激活'FunctionApp2.Function1'时无法解析类型为'FunctionApp2.IClass1'的服务.
Unable to resolve service for type 'FunctionApp2.IClass1' while attempting to activate 'FunctionApp2.Function1'.
这是简单的可复制代码.
Here's the simple reproducable piece of code.
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);
}
}
在functionsStartup
中,我评论了我的注册
In the functionsStartup
i commented my registration
[assembly: FunctionsStartup(typeof(Startup))]
namespace FunctionApp2
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
//builder.Services.AddSingleton<IClass1, Class1>();
}
}
}
这篇关于依赖项注入在Azure函数中缺少注册时注入null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!