Skip to content

Output formatter unexpectedly returns new instance of scoped service #61803

@HaoQian-MS

Description

@HaoQian-MS

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

We have a middleware and a scoped service "IRequestTelemetryContext " in our service.
Then we initialized the scoped service in the middleware. Simplified code:

public Task InvokeAsync(HttpContext context, IRequestTelemetryContext telemetryContext) 
{
   telemetryContext.StartTimeStamp = DateTime.UtcNow;
}

The "StartTimeStamp" is not updated by any other code. Then, in output formatter, we get its value back. Simplified code:

public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
{
   var telemetryContext = context.HttpContext.RequestServices.GetService(typeof(IRequestTelemetryContext)) as IRequestTelemetryContext;
   return Task.Run(() =>
   {
        var startTimeStamp = telemetryContext.StartTimeStamp;
        // Some other code omitted
   }
}

The issue is that occasionally (at low frequency) the "StartTimeStamp" returned is DateTime.MinValue instead of the value we set in middleware. It's unexpected. Scoped service is supposed to be the same instance throughout the request.

Expected Behavior

startTimeStamp should not be the default value of DateTime.

Steps To Reproduce

No response

Exceptions (if any)

No response

.NET Version

No response

Anything else?

Project target framework is net8.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    ✔️ Resolution: AnsweredResolved because the question asked by the original author has been answered.Status: Resolvedarea-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templates

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions