【发布时间】:2018-06-16 06:45:30
【问题描述】:
我正在使用 AspNetCore.SignalR,我需要有关如何通过我的 Hub 访问我的 SQL Server 数据库的建议。关于这方面的资源并不多。我知道如何添加单例,但我不知道以后如何访问它。如何访问在我的 Hub 任务内的 Startup.cs 中使用 Configuration.GetConnectionString 定义的数据库上下文?
谢谢。
以下是相关代码:
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();
}
但我根本不知道在我的 Hub 文件中做什么。我什至不知道从哪里开始。我添加了单例,但我不知道如何在我的集线器文件中访问它。这是我想做的,但我愿意接受更好的方法:
MyHub.cs
using (PlayerContext dbContext = new PlayerContext(/* Singleton needs to go here */))
{
// do database stuff
}
【问题讨论】:
-
你能告诉我们你的代码吗?
-
我添加了它。使用这样的上下文只是我可以做到这一点的一种方式,我对任何事情都持开放态度,我只需要从我的 Hub 类内部访问数据库(最好不直接执行 SQL)。
标签: c# signalr dbcontext signalr-hub asp.net-core-signalr