Access DB context through SignalR Core

前端 未结 3 770
耶瑟儿~
耶瑟儿~ 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:18

    Seems like accessing scoped services still is not documented. But looking to the source code we can see that DefaultHubDispatcher creates scope and hub instance on an every invocation. It means we can use DbContext and other scoped services like we use to do it in asp.net core controllers.

    New DbContext instance is injected into the hub constructor on every hub method invocation. When invocation is completed DbContext gets disposed.

    Startup.cs:

    services.AddDbContext<PlayerContext>(
        options => { options.UseSqlServer(Configuration.GetConnectionString("Default")); },
        ServiceLifetime.Scoped
    );
    

    Hub:

    public class PlayerHub
    {
        private readonly PlayerContext _dbContext;
        public PlayerHub(PlayerContext dbContext)
        {
           _dbContext = dbContext;
        }
        // using _dbContext 
    }
    
    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
  • 2021-01-03 13:21

    I tested this code with .NET Core 3!

    You have to add your DBContext to DI so you can get it from the Constructor of your Hub.

    public class MyHub
    {
          private PlayerContext dbContext;
     
          public MyHub(PlayerContext dbContext)
          {
               this.dbContext = dbContext;
          }
    
          public void YourMethod()
          {
               //call the dbContext here by Dot Notaition
          }
    }
    
    0 讨论(0)
提交回复
热议问题