2

I want to inject instances of the objects directly in Azure function method/body like this:

[FunctionName("StartJob")]
public async Task<IActionResult> Start(
    [HttpTrigger(AuthorizationLevel.Function, "Post", Route = "v1/job")] HttpRequest req,
    IStartJobHandler handler)
{
...

But I got an runtime error when I do this:

The 'StartJob' function is in error: Microsoft.Azure.WebJobs.Host: Error indexing method 'StartJob'. Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'handler' to type IStartJobHandler. Make sure the parameter Type is supported by the binding. If you're using binding extensions (e.g. Azure Storage, ServiceBus, Timers, etc.) make sure you've called the registration method for the extension(s) in your startup code (e.g. builder.AddAzureStorage(), builder.AddServiceBus(), builder.AddTimers(), etc.).

If I inject the same instance in constructor - everything is good. (So no need to suggest me check my startup class and so on :))

I don't want to inject in the constructor though. Because the instance belongs only for one specific function and the idea is to isolate the instances between functions.

So, the question is: can I actually inject custom classes in azure function method directly, without writing additional code, like ILogger for example:

[FunctionName("StartJob")]
public async Task<IActionResult> Start(
    [HttpTrigger(AuthorizationLevel.Function, "Post", Route = "v1/job")] HttpRequest req,
    ILogger logger)
{
...

Or, it's just not supported?

Thanks.

cortisol
  • 335
  • 2
  • 18
  • 1
    Does this answer your question? [DI in Azure Functions](https://stackoverflow.com/questions/45912224/di-in-azure-functions) – Johnny Feb 13 '20 at 15:39
  • Thanks for response. I reformulated the question, I wanted to know the way to avoid writing something additionally... – cortisol Feb 13 '20 at 16:10
  • try specify [FromServices] before IStartJobHandler. It's valid for aspnet core apps, not sure if it works for functions too. – Thiago Custodio Feb 13 '20 at 16:38
  • 1
    Other option is to write you own custom binding. https://github.com/Azure/azure-webjobs-sdk/wiki/Creating-custom-input-and-output-bindings Honestly, if this is going to be used only by one service I think it is not worth it. Is creating an instance of a class that implements the ```IStartJobHandler ``` also and option. (I have information available of IStartJobHandler) – Zsolt Bendes Feb 14 '20 at 07:25

1 Answers1

2

Injecting custom class directly into Function is not possible, you still need to inject constructor to achieve your idea. If you don't choose to inject the constructor, the dependencies will be unavailable. Writing additional code is necessary. This is the right way:

https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection#use-injected-dependencies

Cindy Pau
  • 13,085
  • 1
  • 15
  • 27