简体   繁体   中英

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.

Below is my Startup class.

[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.

在此处输入图片说明

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. 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 .

In addition to making the function a non static member, you should make the function return a Task and await the async function call.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM