【问题标题】:Clean database on application startup在应用程序启动时清理数据库
【发布时间】:2019-10-31 14:27:02
【问题描述】:

我采用了一种方法,将signalr 与用户的连接映射到我的aspnet core 3.0 应用程序。 我所指的方法在Mapping SignalR Users to ConnectionsPermanent, external storage 部分中进行了概述。我知道这篇文章是为不同版本的 Asp.Net 编写的,但它派上了用场。

这是 Hub 的代码:

public class SomeHub : Hub
{
    private readonly UserManager _userManager;
    private readonly AppDbContext _dbContext;

    protected BaseHub(UserManager userManager, AppDbContext dbContext)
    {
        _userManager = userManager;
        _dbContext = dbContext;
    }

    public override async Task OnConnectedAsync()
    {
        var user = await _userManager.GetMe();
        user.Connections.Add(new Connection { ConnectionId = Context.ConnectionId });
        await _dbContext.SaveChangesAsync();
        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception ex)
    {
        var user = await _userManager.GetMe();
        if (await _dbContext.Connections.FindAsync(Context.ConnectionId) is {} connection)
        {
            user.Connections.Remove(connection);
            await _dbContext.SaveChangesAsync();
        }

        await base.OnDisconnectedAsync(ex);
    }
}

问题

如果我拆除我的应用程序,Connection 数据库条目将保留在我的数据库中,因为未调用 OnDisconnectedAsync 方法。

是否有可能在应用程序启动后删除这些条目?

【问题讨论】:

  • 该文档适用于旧的 ASP.NET SignalR,而不是 ASP.NET Core SignalR。文章顶部的彩色面板中有一个非常强烈的警告:This documentation isn't for the latest version of SignalR. Take a look at ASP.NET Core SignalR.
  • 这是真的,请查看问题的更新版本。似乎仍然没有最新版本的匹配文章。至少我没有找到。

标签: c# asp.net-core entity-framework-core signalr c#-8.0


【解决方案1】:

在调用AddDbContext之后,我需要在Startup类的Configure方法中添加以下代码:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AppDbContext>([...]);

    using (var serviceProvider = services.BuildServiceProvider())
    using (var serviceScope = serviceProvider.CreateScope())
    using (var context = scope.ServiceProvider.GetService<AppDbContext>())
    {
        context.Connections.RemoveRange(context.Connections);
        context.SaveChanges();
    }
    [...]
}

【讨论】:

  • 如果你不想要持久连接,为什么要使用数据库?除非您想部署到场?
  • @PanagiotisKanavos 使用 signalr,单个物理用户可以使用多个设备、选项卡和浏览器连接到同一个集线器。此外,存储的连接还可以帮助我在请求时向信号器组添加和删除用户。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-05
  • 2015-03-20
  • 1970-01-01
  • 2015-06-26
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
相关资源
最近更新 更多