【问题标题】:Dbcontext object transient in dotnet coredotnet 核心中的 Dbcontext 对象瞬态
【发布时间】:2018-01-19 04:54:54
【问题描述】:

我正在使用实体框架在 dotnet 核心中创建一个 webapi 应用程序。当我浏览文档时。我可以使用 DI 在 dotnet core 中注入 dbcontext 对象。但是当我这样做时,整个应用程序都使用一个 dbcontext 对象。如何将 dbcontext 设为瞬态?如果有任何例子,它真的会帮助我。

请在下面找到我现有的代码。

这是我在 ConfigureService 中写的代码

  public void ConfigureServices(IServiceCollection services)
        {
           services.AddDbContext<DataAccess.XXXXContext>(options => options.UseMySQL(Configuration["ConnectionStrings:DefaultConnection"]),ServiceLifetime.Transient);
        }

这是我在 DBcontext 类中写的代码

 public partial class XXXXContext : DbContext
    {
        private readonly Logger logger = LogManager.GetCurrentClassLogger();

        public XXXXContext(DbContextOptions<XXXXContext> options) :base(options)
        {
            logger.Debug("XXXXContext created");
        }
     }

如果你看到我已经在 AddDbContext 方法中编写了 Transient。所以每次如果它创建对象。我的构造函数应该调用。但我只接到一次电话。

【问题讨论】:

  • 我们需要看看你的代码老兄......
  • 我已经用源代码编辑了我的帖子

标签: entity-framework-core


【解决方案1】:

我已经使用单独的语句完成了此操作。

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<DataAccess.XXXXContext>(options => options.UseMySQL(Configuration["ConnectionStrings:DefaultConnection"]));

    services.AddTransient<DataAccess.XXXXContext>();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-03
    • 2012-12-07
    • 2023-03-21
    • 2011-06-17
    • 2016-11-22
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多