gaa*_*kam 1 singleton entity-framework-core asp.net-core
我想将完成的国际象棋游戏存储在数据库中,以支持用户观看重播。
到目前为止,我有一个单例GameManager
存储所有正在进行的游戏。因此,startup.cs
我有以下代码行:
services.AddSingleton<IBattleManager, BattleManager>();
Run Code Online (Sandbox Code Playgroud)
现在,我想BattleManager
访问DbContext
保存已完成的游戏。
public class BattleManager : IBattleManager
{
//...
private void EndGame(ulong gameId)
{
var DbContext = WhatDoIPutHere?
lock(gameDictionary[gameId])
{
DbContext.Replays.Add(new ReplayModel(gameDictionary[gameId]));
gameDictionary.Remove(gameId)
}
}
}
Run Code Online (Sandbox Code Playgroud)
是否有可能实现这一目标?怎么样?
尝试失败:
public class BattleManager : IBattleManager
{
Data.ApplicationDbContext _context;
public BattleManager(Data.ApplicationDbContext context)
{
_context = context;
}
}
Run Code Online (Sandbox Code Playgroud)
这显然会失败,因为无法DbContext
像这样将EF Core 注入到Singleton服务中。
我有一种模糊的感觉,我应该做这样的事情:
using (var scope = WhatDoIPutHere.CreateScope())
{
var DbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
DbContext.Replays.Add(new ReplayModel(...));
}
Run Code Online (Sandbox Code Playgroud)
这是正确的方向吗?
您走在正确的轨道上。该IServiceScopeFactory
能做到这一点。
public class BattleManager : IBattleManager {
private readonly IServiceScopeFactory scopeFactory;
public BattleManager(IServiceScopeFactory scopeFactory)
{
this.scopeFactory = scopeFactory;
}
public void MyMethod() {
using(var scope = scopeFactory.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<DbContext>();
// when we exit the using block,
// the IServiceScope will dispose itself
// and dispose all of the services that it resolved.
}
}
}
Run Code Online (Sandbox Code Playgroud)
的DbContext
行为就像Transient
在该using
语句中具有作用域一样。
归档时间: |
|
查看次数: |
1025 次 |
最近记录: |