Search code examples
c#signalrdbcontextsignalr-hubasp.net-core-signalr

Access DB context through SignalR Core


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 add a singleton but I do not know how to access it later. How can I access a DB context that is defined using a Configuration.GetConnectionString in Startup.cs inside my Hub's Tasks?

Thanks.

Here's the relevant code:

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
        });


    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    DbContextOptionsBuilder<PlayerContext> PlayerContextOptions = new DbContextOptionsBuilder<PlayerContext>();
    PlayerContextOptions.UseSqlServer(Configuration.GetConnectionString("Default"));
    services.AddSingleton(PlayerContextOptions.Options);

    services.AddDbContext<PlayerContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));



    services.AddCors(options => options.AddPolicy("CorsPolicy",
        builder =>
        {
            builder.AllowAnyMethod().AllowAnyHeader()
            .AllowCredentials();
            }));

    services.AddSignalR();
} 

But I don't know what to do in my Hub file at all. I don't even know where to start. I added the singleton but I don't know how to access it in my hub file. This is what I would like to do, but I'm open to a better way of doing it:

MyHub.cs

using (PlayerContext dbContext = new PlayerContext(/* Singleton needs to go here */))
{
    // do database stuff
} 

Solution

  • 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
          }
    }