Access DB context through SignalR Core

前端 未结 3 793
耶瑟儿~
耶瑟儿~ 2021-01-03 12:36

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

3条回答
  •  星月不相逢
    2021-01-03 13:20

    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();
    }
    

提交回复
热议问题