实体框架核心内存泄漏?

时间:2020-04-24 18:13:06

标签: c# memory-leaks ef-core-3.0

我将EntityFrameworkCore用于带有MySQL数据库的Discord Bot。就其本身而言,一切工作都很好,但是每次我访问DbContext时,都会创建一些不再被丢弃的对象。在Visual Studio诊断工具中,经过几个数据库查询后,它看起来像这样: enter image description here

这是我将实体框架集成到程序中的方式:

var services = new ServiceCollection().AddDbContext<DatabaseContext>(x => x.UseMySql("server=localhost;database=testdb;user=root"));

这将调用我的扩展方法:

public static IServiceCollection AddDbContext<TContext>(this IServiceCollection This,
            Action<DbContextOptionsBuilder> optionsBuilder)
            where TContext : DbContext
        {
            return This
                .AddSingleton(x =>
                {
                    var builder = new DbContextOptionsBuilder<TContext>();
                    optionsBuilder(builder);
                    return builder.Options;
                })
                .AddTransient<TContext>()
                .AddTransient<DbContext>(x => x.GetRequiredService<TContext>());
        }

我的DatabaseContext如下:

public class DatabaseContext : DbContext
{
     public DbSet<GuildEntity> Guilds { get; set; }

     public DatabaseContext(DbContextOptions<DatabaseContext> options)
                : base(options)
     {
     }

     protected override void OnModelCreating(ModelBuilder modelBuilder)
     {
          modelBuilder.Entity<GuildEntity>(entity =>
          {
              entity.Property(x => x.Level).HasDefaultValue(true);

              entity.Property(x => x.Notify).HasDefaultValue(false);

              entity.Property(x => x.Log).HasDefaultValue(false);

              entity.Property(x => x.Trash).HasDefaultValue(false);
          });
     }
}

我也有这个DatabaseService,我得到了DatabaseContext

public class DatabaseService
{
    private readonly IServiceProvider _serviceProvider;

    public DatabaseService(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public TContext Open<TContext>() where TContext : DbContext
    {
        return _serviceProvider.GetRequiredService<TContext>();
    }
}

这就是我执行数据库查询的方式:

using (var db = _databaseService.Open<DatabaseContext>())
{
    var guilds = db.Guilds.Where(p => p.GuildName == "MyGuild");
}

即使我在查询中包含AsNoTracking(),也会为此查询创建从不丢弃的对象。

我完全不知道我的错误在哪里,我希望我的例子足以看到错误。如果没有,这是我的Discord Bot的GitHub存储库:Code of my bot

0 个答案:

没有答案