Functions and Dependency Injection
Functions and Dependency Injection

Dependency Injection in .NET Based Azure Functions

We already have seen that there are two different execution models for .NET Based Azure Functions. The two execution models are in-process and isolated worker process. In this article, we are going to have a quick overview of how to setup dependency injection in .NET Based Azure Functions.

In-Process Functions

As we know, In-Process functions can be of two types –

  • Functions which contain C# Script (.csx) files
  • In-Process Class Library Functions

Whatever we discuss in this section is going to be applicable only for in-process class library functions. We have created one In-Process class library function in one of the previous articles. Refer this article to create the project.

Once the project is created, add a new class Startup to the class library. Then let’s add a package Microsoft.Azure.Functions.Extensions to this project. In the Startup class, we can do two things:

  • Add an assembly attribute FunctionsStartup, and pass the fully qualified name of the Startup class
  • Inherit the Startup class from FunctionsStartup

The code snippet given below shows a sample code of Startup class. In addition to startup class, the code snippet also shows a sample service interface and its implementation. This service is then registered in the dependency injection container in the Startup class.

Now, we can inject IMyService to any function, and if we run the function, the passed message will be logged to the console.

In-Process Class Library Functions and Dependency Injection

So, now we know how the dependency injection can also be set up in Azure Functions.

Isolated Worker Process Functions

We already know that these type of functions are console applications, which runs independently of the host process. This kind of Azure function creates an IHost instance. This IHost instance can be used for setting up dependency injection for the process. The code for setting up dependency injection is going to be similar to any ASP .NET Core web application.

I hope you find this information helpful. Let me know your thoughts.

Leave a ReplyCancel reply