C# Azure Functions support dependency injection through the native container.
This allows us to use the Dependency Inject principle in native Azure Functions. In this post, we're going to create a simple function to demonstrate the use of it.
Azure Functions allows you to run small pieces of code (called "functions") without worrying about application infrastructure. With Azure Functions, the cloud infrastructure provides all the up-to-date servers you need to keep your application running at scale.
For this demonstration, we're going to use this
RandomNumberService to Inject into our function.
Install/Update the following NuGet packages in your project.
Registering the Services in the Container
To register the services and we're going to create a startup function, just like we have in a common asp.net core application.
Create a file called
FunctionStartup.cs at the root of your application.
Paste the following content into the file.
Before the namespace we're registering our class as a dependency start the function
It will tell the function runtime to trigger our class before serving HTTP requests.
Ps.: Do not use to process other things, only to register services.
FunctionStartup we gain access to
IFunctionsHostBuilder object where we can register all dependencies, such as Scoped, Transient, or Singleton.
- Transient: Transient services are created upon each request of the service.
- Scoped: The scoped service lifetime matches a function execution lifetime. Scoped services are created once per execution.
- Singleton: The singleton service lifetime matches the host lifetime and is reused across function executions on that instance.
Using the service though Dependency Injection
Open your function file do the following changes
staticmarker from the class and the function (we need to inject using constructors)
- Create a constructor and inject the dependency interface
You should end with something like this:
Run the application and access the URL for testing.
Hope you like it. Subscribe for more fresh content.