Azure / Azure/azure-functions-dotnet-worker

FunctionContext is not accessible through dependency injection

Open
#574 7 comments 11 reactions 1 assignee Claimed by @fabiocav View on GitHub
needs-discussion
Dominant language
C#
Stars
466
Forks
215
Avg merge
3d 10h
Merged PRs (30d)
7

Description

With the introduction of the [FunctionContext](https://github.com/Azure/azure-functions-dotnet-worker/blob/main/src/DotNetWorker.Core/Context/FunctionContext.cs) in the dotnet-isolated (.NET 5) runtime environment for Azure Functions, we now have an easy way to access common Function information and share arbitrary data through the Items property on that context. Unfortunately, although you can access the FunctionContext through middleware and as a direct Function parameter, it is not currently available through dependency injection.

> Exception: System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Azure.Functions.Worker.FunctionContext'...

So, two things:

First, a question: is there some other way to access the FunctionContext through dependency injection? I've poked around the code and documentation and haven't found anything yet. Can any of the [default injected services](https://github.com/Azure/azure-functions-dotnet-worker/blob/dee65e78cbd22ce884dca653f594f0e509c40837/src/DotNetWorker.Core/Hosting/ServiceCollectionExtensions.cs#L31) access it?

Second, a request: could we have a specific service added by default to access the FunctionContext through DI? Perhaps an `IFunctionContextAccessor` that would work very similarly to [`IHttpContextAccessor`](https://github.com/dotnet/aspnetcore/blob/main/src/Http/Http/src/HttpContextAccessor.cs), which would return the FunctionContext for the current invocation.

In the meantime, I'm attempting to implement my own version of this by grabbing the FunctionContext in a [custom middleware](https://docs.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide#middleware) and setting it to an AsyncLocal, which can then be referenced by injected services. If it works, I'll come back and post an example here.

UPDATE: Here's my example of an [implementation of IFunctionContextAccessor](https://gist.github.com/dolphinspired/796d26ebe1237b78ee04a3bff0620ea0), which you can start using in your dotnet-isolated Functions today!

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.