azure-functions-host
azure-functions-host copied to clipboard
DI Scope for Function class constructor and HttpContext are different
Investigative information
Please provide the following:
- Function App version: 4.6.1.18388
Repro steps
Run a basic Azure Function project with the following code:
public interface ISomeScopedService {}
public class SomeScopedService : ISomeScopedService {}
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddScoped<ISomeScopedService, SomeScopedService>();
}
}
public class SampleFunction
{
private readonly ISomeScopedService ctorInjectedService;
public SampleFunction(ISomeScopedService service)
{
this.ctorInjectedService = service;
}
[FunctionName("SampleFunction")]
public async Task<IActionResult> SampleFunction(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "sample")] HttpRequest request)
{
var httpContextService = request.HttpContext.RequestServices.GetRequiredService<ISomeScopedService>();
var same = object.ReferenceEquals(ctorInjectedService, httpContextService);
return new OkObjectResult(same);
}
}
Expected behavior
The injected services are the same instance because both were resolved within the scope and the service has a scoped lifetime.
Actual behavior
The injected services are different instances
Known workarounds
Stop using constructor injection for scoped services and httpContext.RequestServices
Hi @fabiocav Could you please help with this issue?
Hi @richardszalay You may want to go through this Please let us know if it helps
Hi @Ved2806, I'm not sure how that documentation helps with this particular issue. Can you clarify why you shared that particular documentation link?
This issue has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for 4 days. It will be closed if no further activity occurs within 3 days of this comment.