Access DB context through SignalR Core

前端 未结 3 787
耶瑟儿~
耶瑟儿~ 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(
        options => { options.UseSqlServer(Configuration.GetConnectionString("Default")); },
        ServiceLifetime.Scoped
    );
    

    Hub:

    public class PlayerHub
    {
        private readonly PlayerContext _dbContext;
        public PlayerHub(PlayerContext dbContext)
        {
           _dbContext = dbContext;
        }
        // using _dbContext 
    }
    

提交回复
热议问题