[英]Azure Function with Dependency Injection doesn't create instance of my service
I am following this post, and implemented the Startup
class so that I can inject my services in the constructor, but the service instance is always null and I am getting Object reference not set to an instance of an object
when I run the application.我正在关注这篇文章,并实现了
Startup
类,以便我可以在构造函数中注入我的服务,但服务实例始终为空,并且我在运行应用程序时Object reference not set to an instance of an object
。
Below is my Startup
class.下面是我的
Startup
课程。
[assembly: FunctionsStartup(typeof(Backup.Functions.Startup))]
namespace Backup.Functions {
public class Startup: FunctionsStartup {
public override void Configure(IFunctionsHostBuilder builder) {
builder.Services.AddSingleton < IBlobService,
BlobService > ();
}
}
}
My Function code is as below.我的功能代码如下。
public class DeleteDailyBlobs {
private static IBlobService _blobService;
public DeleteDailyBlobs(IBlobService blobService) {
_blobService = blobService;
}
[FunctionName("DeleteDailyBlobs")]
public static void Run([TimerTrigger("0/3 * * * * *")] TimerInfo myTimer, ILogger log) {
if (_blobService.PerformTasks().GetAwaiter().GetResult()) {
log.LogInformation(SuccessMessages.FunctionExecutedSuccessfully);
}
else {
log.LogError(ErrorMessages.SomethingBadHappened);
}
}
}
Here the _blobService
is always null.这里
_blobService
始终为空。
Finally I was able to find what was the issue, unfortunately I forgot to mark my function non static
, so all I had to do was to remove the static
keyword from my Azure Function.最后我找到了问题所在,不幸的是我忘记将我的函数标记为
non static
,所以我所要做的就是从我的 Azure 函数中删除static
关键字。 After removing that, everything was fine.删除后,一切正常。
public void Run([TimerTrigger("0/3 * * * * *")]TimerInfo myTimer, ILogger log)
Hope it helps.希望能帮助到你。
As Nkosi was mentioning we should mark the return type of the Function as Task
and I have written an article about this, and can be found here .正如 Nkosi 所提到的,我们应该将函数的返回类型标记为
Task
,我已经写了一篇关于此的文章,可以在这里找到。
In addition to making the function a non static member, you should make the function return a Task
and await the async function call.除了使函数成为非静态成员之外,您还应该使函数返回一个
Task
并等待异步函数调用。
public class DeleteDailyBlobs {
private readonly IBlobService blobService;
public DeleteDailyBlobs(IBlobService blobService) {
this.blobService = blobService;
}
[FunctionName("DeleteDailyBlobs")]
public async Task Run([TimerTrigger("0/3 * * * * *")] TimerInfo myTimer, ILogger log) {
if (await blobService.PerformTasks()) {
log.LogInformation(SuccessMessages.FunctionExecutedSuccessfully);
}
else {
log.LogError(ErrorMessages.SomethingBadHappened);
}
}
}
And since the dependency is also being added as a singleton, there really is no need to make it a static field as well.而且由于依赖项也是作为单例添加的,因此确实没有必要将其也设为静态字段。 The instance will be the same where ever it is injected.
实例将在注入时相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.