azure-functions-host icon indicating copy to clipboard operation
azure-functions-host copied to clipboard

DI Scope for Function class constructor and HttpContext are different

Open richardszalay opened this issue 3 years ago • 1 comments

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

richardszalay avatar Jul 14 '22 12:07 richardszalay

Hi @fabiocav Could you please help with this issue?

Ved2806 avatar Jul 18 '22 05:07 Ved2806

Hi @richardszalay You may want to go through this Please let us know if it helps

Ved2806 avatar Nov 02 '22 10:11 Ved2806

Hi @Ved2806, I'm not sure how that documentation helps with this particular issue. Can you clarify why you shared that particular documentation link?

richardszalay avatar Nov 02 '22 11:11 richardszalay

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.

ghost avatar Nov 06 '22 13:11 ghost