【问题标题】:DbContext instance vs Scope instanceDbContext 实例与 Scope 实例
【发布时间】:2019-03-08 10:01:54
【问题描述】:

为什么 Entity Framework 使用 AddDbContext 方法进行依赖注入,而不是 Singleton、Scoped、Transient?

使用AddDbContext 方法,我们为每个请求获得了什么样的服务生命周期(Singleton、Scoped、Transient)?

【问题讨论】:

  • 默认情况下 AddDbContext 使用 Scoped 生命周期。它对于每个请求都定义一个范围的 Web 应用程序最有用。这可确保在请求的生命周期内可以使用相同的上下文。如果上下文仅在动作内部使用,瞬态也很有用

标签: c# asp.net-core dependency-injection


【解决方案1】:

该方法的无参数版本导致DbContextScoped生命周期,如果给定,选项:

        public static IServiceCollection AddDbContext<TContext>(
        [NotNull] this IServiceCollection serviceCollection,
        [CanBeNull] Action<DbContextOptionsBuilder> optionsAction = null,
        ServiceLifetime contextLifetime = ServiceLifetime.Scoped,
        ServiceLifetime optionsLifetime = ServiceLifetime.Scoped)
        where TContext : DbContext
        => AddDbContext<TContext, TContext>(serviceCollection, optionsAction, contextLifetime, optionsLifetime);

AddDbContext 只是 Entity Framework Core 提供的一种扩展方法,它在后台为您处理服务注册。您可以自己完成所有在那里完成的服务注册,但是使用这种扩展方法,EFCore 可以确保一切都根据需要进行设置。

该方法有一个重载,您可以在其中自己指定ServiceLifetime(使用无参数重载的默认参数调用)。

一般来说,对于这类问题,最容易查阅官方文档:

EntityFrameworkServiceCollectionExtensions.AddDbContext Official Doc

或者更深入的了解,看github上的Code:

EF-Core Github

【讨论】:

    猜你喜欢
    • 2011-07-10
    • 2019-03-07
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2013-03-07
    • 1970-01-01
    • 2021-12-30
    相关资源
    最近更新 更多