none
Saving persistence in SignalR Core hub RRS feed

  • Question

  • I have a .Net Core 2.2 Web API for a chat app with a SignalR hub. I'd like to save the chats to the database (MySQL). At first I thought I could inject my DbContext into the hub via dependency injection. But then I read that the hub is Singleton whereas the DbContext (when used via the AddDbContext helper) is Scoped. I then read another post where it was suggested to force AddDbContext to add the context as singleton. But I've also read this is a really bad idea. Finally I read a post where someone suggested simply getting the DbContext from within my Hub by using DbContextFactory, and they provided this example:

    using (var dbContextScope = dbContextScopeFactory.Create(options))
    {
        //do database stuff
        dbContextScope.SaveChanges();
    }
    

    However, I don't know how to get an instance of DbContextScopeFactory in my hub. I tried injecting IDbContextScopeFactory into my hub's constructor, but it just says that the type or namespace IDbContextScopeFactory could not be found

    Could anyone perhaps point me in the right direction?

    Thanks


    Fabricio Rodriguez - Pretoria, South Africa

    • Moved by CoolDadTx Thursday, June 6, 2019 1:53 PM ASP.NET related
    Wednesday, June 5, 2019 1:54 PM

All replies

  • Hi Fabs1977,

    Thank you for posting here.

    Since this thread is related to .net core Web API, I suggest that you could post in the following forum.

    https://forums.asp.net/1255.aspx/1?ASP+NET+Core

    The Visual C# forum discusses and asks questions about the C# programming language, IDE, libraries, samples, and tools.

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, June 6, 2019 1:33 AM
  • Thanks you Jack. I have done so.

    Fabricio Rodriguez - Pretoria, South Africa

    Thursday, June 6, 2019 5:24 AM
  • You have the 3 DI container scopes for .NET Core based solution for ASP.NET and Windows desktop Core.

    https://dotnetcoretutorials.com/2017/03/25/net-core-dependency-injection-lifetimes-explained/

    Thursday, June 6, 2019 7:39 AM