首页 > 解决方案 > 内存数据库注册 InstancePerDependency System.OutOfMemoryException

问题描述

我正在更新 DbContext 的注册方式。在单元测试中,注册内存数据库的旧方法如下

builder.RegisterInstance(new DbContextOptionsBuilder<OneContext>()
                 .UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
builder.RegisterType<OneContext>().InstancePerDependency();

我使用 AddDbContext 的新方法

services.AddDbContext<OneContext>(options => options
                .UseInMemoryDatabase(Guid.NewGuid().ToString()), ServiceLifetime.Transient);

在解析为 InstancePerDependency 时,我使用了每个上下文的范围,就像按照文章中的一篇一样。

  using (ILifetimeScope scope = container.BeginLifetimeScope("KEY"))
    {
      scope.Resolve<IService>(); // Instance #1

      using (ILifetimeScope childScope = scope.BeginLifetimeScope())
      {
         childScope.Resolve<DbContext>();
         childScope.Resolve<IService>(); 
      }
    }

我在这里做错了什么?你介意让我知道吗。

标签: c#.net.net-coreautofacin-memory-database

解决方案


推荐阅读