Skip to content

Add Documentation on how to inject/access DBContext or information on scoped services in SignalR #9658

@TrieBr

Description

@TrieBr

The documentation is not clear how to inject and work with a DBContext or scoped service in SignalR, which I believe would be a fairly common scenario. Hubs have a Transient lifetime. According to the dependency injection documentation it says "Services that use the database context should also use the scoped lifetime". It's not clear how scoped services are handled in signalR.

I'm currently having an issue resulting in error A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe. on my DBContext intermittently. I have a feeling this is related to the difference in my Scoped DBContext and Transient Hub. In a normal HTTP request it's clear that a "Scoped" service is created at the beginning of each http request. However in a websocket situation, when is a Scoped service created? Is the scoped service created when the socket establishes connection and the scope ends when the socket is disconnected? It seems like my problem is due to a Transient Hub using the same scoped service across multiple Hub method calls resulting in the threading error mentioned above.

Note: I've already checked for async method invocations that are missing await expressions using Regex and ReSharper, and have found none. I've never had this much of a problem on normal controllers so I'm led to believe this is an issue with how SignalR handles scoped services which isn't documented.


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions