I\'m using AspNetCore.SignalR and I need advice on how to access my SQL Server database through my Hub. There are not a lot of resources out there about this. I know how to
Using the dependency injection on SignalR hub's to inject EF DbContext is a wrong choice, because SignalR hub itself is a Singleton and shouldn't have dependencies with the lower lifetime cycle, you will end up with a warnings. That means, that you cant register your DbContext with PerRequest/Transient lifetime scopes, only with singleton. Registering DbContext as Singleton is a very bad choice. Making new context isn't expensive, but your hub with a singleton context will grow exponentially after some time.
I suggest using the DbContextFactory for the Hub classes, in your hub ask the new DbContext from the factory and put it to the using statement. You could also register factory itself as a Singleton and make dependency in hub constructor more clear.
using (var dbContextScope = dbContextScopeFactory.Create(options))
{
//do database stuff
dbContextScope.SaveChanges();
}