Azure / Azure/azure-functions-host
AddSingleton with disposable instance behaviour
- Dominant language
- C#
- Stars
- 2k
- Forks
- 482
- Avg merge
- 2d 12h
- Merged PRs (30d)
- 38
Description
#### Is your question related to a specific version? If so, please specify:
v2 - 2.0.13351.0
#### What language does your question apply to? (e.g. C#, JavaScript, Java, All)
C#
#### Question
Trying to use function DI to register IDocumentClient (cosmos) as a Singleton. DocumentClient is disposable.
The documentation at https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection suggests that "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."
However it seems like the singleton is being disposed after the first request, and on subsequent requests getting an ObjectDisposedException:
```
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'DocumentClient'.
at Microsoft.Azure.Documents.Client.DocumentClient.ThrowIfDisposed()
at Microsoft.Azure.Documents.Client.DocumentClient.EnsureValidClientAsync()
at Microsoft.Azure.Documents.Client.DocumentClient.GetCollectionCacheAsync()
```
It feels like something is not quite right here. Is this the correct behaviour for a disposable singleton or a bug? I've had a quick search and found issues with scoped being disposed incorrectly, but haven't found anything regarding singleton.
Cheers
Contributor guide
Research direction
Start with the Azure Functions dependency-injection documentation linked in the issue and the reported v2 environment. Reproduce the singleton registration using the disposable Cosmos DocumentClient, then trace when it is disposed across successive function executions. Done means determining whether the disposal is expected or a host bug and documenting the lifecycle behavior or a focused fix.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- azure, csharp
- Domain
- backend, cloud
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 35/100