You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Use dependency injection in .NET Azure Functions
18
18
19
19
Azure Functions supports the dependency injection (DI) software design pattern, which is a technique to achieve [Inversion of Control (IoC)](https://docs.microsoft.com/dotnet/standard/modern-web-apps-azure-architecture/architectural-principles#dependency-inversion) between classes and their dependencies.
20
20
21
-
Azure Functions builds on top of the ASP.NET Core Dependency Injection features. Being aware of services, lifetimes, and design patterns of [ASP.NET Core dependency injection](https://docs.microsoft.com/aspnet/core/fundamentals/dependency-injection)before using DI features in an Azure Functions app is recommended.
21
+
- Dependency injection in Azure Functions is built on the .NET Core Dependency Injection features. Familiarity with the [.NET Core dependency injection](https://docs.microsoft.com/aspnet/core/fundamentals/dependency-injection)is recommended. There are differences, however, in how you override dependencies and how configuration values are read with Azure Functions on the Consumption plan.
22
22
23
-
Support for dependency injection begins with Azure Functions 2.x.
23
+
-Support for dependency injection begins with Azure Functions 2.x.
24
24
25
25
## Prerequisites
26
26
@@ -30,21 +30,18 @@ Before you can use dependency injection, you must install the following NuGet pa
30
30
31
31
-[Microsoft.NET.Sdk.Functions package](https://www.nuget.org/packages/Microsoft.NET.Sdk.Functions/) version 1.0.28 or later
32
32
33
-
- Optional: [Microsoft.Extensions.Http](https://www.nuget.org/packages/Microsoft.Extensions.Http/) Only required for registering HttpClient at startup
34
-
35
33
## Register services
36
34
37
-
To register services, you can create a method to configure and add components to an `IFunctionsHostBuilder` instance. The Azure Functions host creates an instance of `IFunctionsHostBuilder` and passes it directly into your method.
35
+
To register services, create a method to configure and add components to an `IFunctionsHostBuilder` instance. The Azure Functions host creates an instance of `IFunctionsHostBuilder` and passes it directly into your method.
38
36
39
-
To register the method, add the `FunctionsStartup` assembly attribute that specifies the type name used during startup. Also code is referencing a prerelease of [Microsoft.Azure.Cosmos](https://www.nuget.org/packages/Microsoft.Azure.Cosmos/) on Nuget.
37
+
To register the method, add the `FunctionsStartup` assembly attribute that specifies the type name used during startup.
A series of registration steps run before and after the runtime processes the startup class. Therefore, the keep in mind the following items:
69
+
70
+
-*The startup class is meant for only setup and registration.* Avoid using services registered at startup during the startup process. For instance, don't try to log a message in a logger that is being registered during startup. This point of the registration process is too early for your services to be available for use. After the `Configure` method is run, the Functions runtime continues to register additional dependencies, which can affect how your services operate.
71
+
72
+
-*The dependency injection container only holds explicitly registered types*. The only services available as injectable types are what are setup in the `Configure` method. As a result, Functions-specific types like `BindingContext` and `ExecutionContext` aren't available during setup or as injectable types.
73
+
67
74
## Use injected dependencies
68
75
69
-
ASP.NET Core uses constructor injection to make your dependencies available to your function. The following sample demonstrates how the `IMyService` and `HttpClient` dependencies are injected into an HTTP-triggered function.
76
+
Constructor injection is used to make your dependencies available in a function. The use of constructor injection requires that you do not use static classes.
77
+
78
+
The following sample demonstrates how the `IMyService` and `HttpClient` dependencies are injected into an HTTP-triggered function. This example uses the [Microsoft.Extensions.Http](https://www.nuget.org/packages/Microsoft.Extensions.Http/) package required to register an `HttpClient` at startup.
70
79
71
80
```csharp
72
81
usingSystem;
@@ -77,7 +86,6 @@ using Microsoft.Azure.WebJobs;
77
86
usingMicrosoft.Azure.WebJobs.Extensions.Http;
78
87
usingMicrosoft.AspNetCore.Http;
79
88
usingMicrosoft.Extensions.Logging;
80
-
usingNewtonsoft.Json;
81
89
82
90
namespaceMyNamespace
83
91
{
@@ -107,24 +115,23 @@ namespace MyNamespace
107
115
}
108
116
```
109
117
110
-
The use of constructor injection means that you should not use static functions if you want to take advantage of dependency injection. For cosmos client refer [this](https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos.Samples/CodeSamples/AzureFunctions/AzureFunctionsCosmosClient.cs).
111
-
112
118
## Service lifetimes
113
119
114
-
Azure Functions apps provide the same service lifetimes as [ASP.NET Dependency Injection](https://docs.microsoft.com/aspnet/core/fundamentals/dependency-injection#service-lifetimes): transient, scoped, and singleton.
120
+
Azure Functions apps provide the same service lifetimes as [ASP.NET Dependency Injection](https://docs.microsoft.com/aspnet/core/fundamentals/dependency-injection#service-lifetimes). For a Functions app, the different service lifetimes behave as follows:
115
121
116
-
In a functions app, a scoped service lifetime matches a function execution lifetime. Scoped services are created once per execution. Later requests for that service during the execution reuse the existing service instance. A singleton service lifetime matches the host lifetime and is reused across function executions on that instance.
117
-
118
-
Singletonlifetime services are recommended for connections and clients, for example `SqlConnection`, `CloudBlobClient`, or `HttpClient` instances.
122
+
-**Transient**: Transient services are created upon each request of the service.
123
+
-**Scoped**: The scoped service lifetime matches a function execution lifetime. Scoped services are created once per execution. Later requests for that service during the execution reuse the existing service instance.
124
+
-**Singleton**: The singleton service lifetime matches the host lifetime and is reused across function executions on that instance. Singleton lifetime services are recommended for connections and clients, for example `SqlConnection` or `HttpClient` instances.
119
125
120
126
View or download a [sample of different service lifetimes](https://aka.ms/functions/di-sample) on GitHub.
121
127
122
128
## Logging services
123
129
124
-
If you need your own logging provider, the recommended way is to register an `ILoggerProvider` instance. Application Insights is added by Azure Functions automatically.
130
+
If you need your own logging provider, register a custom type as an `ILoggerProvider` instance. Application Insights is added by Azure Functions automatically.
125
131
126
132
> [!WARNING]
127
-
> Do not add `AddApplicationInsightsTelemetry()` to the services collection as it registers services that conflict with services provided by the environment.
133
+
> - Do not add `AddApplicationInsightsTelemetry()` to the services collection as it registers services that conflict with services provided by the environment.
134
+
> - Do not register your own `TelemetryConfiguration` or `TelemetryClient` if you are using the built-in Application Insights functionality.
128
135
129
136
## Function app provided services
130
137
@@ -141,6 +148,51 @@ If there are other services you want to take a dependency on, [create an issue a
141
148
142
149
Overriding services provided by the host is currently not supported. If there are services you want to override, [create an issue and propose them on GitHub](https://github.com/azure/azure-functions-host).
143
150
151
+
## Working with options and settings
152
+
153
+
Values defined in [app settings](./functions-how-to-use-azure-function-app-settings.md#settings) are available in an `IConfiguration` instance, which allows you to read app settings values in the startup class.
154
+
155
+
You can extract values from the `IConfiguration` instance into a custom type. Copying the app settings values to a custom type makes it easy test your services by making these values injectable. Consider the following class that includes a property named consistent with an app setting.
156
+
157
+
```csharp
158
+
publicclassMyOptions
159
+
{
160
+
publicstringMyCustomSetting { get; set; }
161
+
}
162
+
```
163
+
164
+
From inside the `Startup.Configure` method, you can extract values from the `IConfiguration` instance into your custom type using the following code:
Calling `Bind` copies values that have matching property names from the configuration into the custom instance. The options instance is now available in the IoC container to inject into a function.
175
+
176
+
The options object is injected into the function as an instance of the generic `IOptions` interface. Use the `Value` property to access the values found in your configuration.
177
+
178
+
```csharp
179
+
usingSystem;
180
+
usingMicrosoft.Extensions.Options;
181
+
182
+
publicclassHttpTrigger
183
+
{
184
+
privatereadonlyMyOptions_settings;
185
+
186
+
publicHttpTrigger(IOptions<MyOptions> options)
187
+
{
188
+
_service=service;
189
+
_settings=options.Value;
190
+
}
191
+
}
192
+
```
193
+
194
+
Refer to [Options pattern in ASP.NET Core](https://docs.microsoft.com/aspnet/core/fundamentals/configuration/options) for more details regarding working with options.
195
+
144
196
## Next steps
145
197
146
198
For more information, see the following resources:
0 commit comments