asp.net-core - AddDbContext()服务类型激活方式

标签 asp.net-core asp.net-core-mvc

当您使用 ASP.NET core RC2 创建新的 Web 应用程序时,它在 Startup.cs 文件中包含以下代码 -

services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

我的问题是 - 注入(inject)此 DbContext 对象的激活模式是什么?它是暂时的、有作用域的还是其他什么?

谢谢。

最佳答案

AddDbContext<TContext>扩展方法在 EntityFrameworkServiceCollectionExtensions.cs 中定义文件在 EntityFrameworkCore并包含以下内容:

serviceCollection.TryAddSingleton(p => DbContextOptionsFactory<TContext>(p, optionsAction));
serviceCollection.AddSingleton<DbContextOptions>(p => p.GetRequiredService<DbContextOptions<TContext>>());

serviceCollection.TryAdd(new ServiceDescriptor(typeof(TContext), typeof(TContext), contextLifetime));

其中 contextLifetime 是 ServiceLifetime.Scoped默认情况下,但可以更改。

请记住,一般来说,您始终可以在 github 上找到并分析 ASP.NET Core 源代码。

关于asp.net-core - AddDbContext()服务类型激活方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37781238/

相关文章:

asp.net - 我在使用asp.net core 2.2应用程序的生产上的facebook登录回调中收到错误500

c# - 我应该在数据库中还是在代码中应用计数?

c# - 在.net core web API中自动添加策略属性

c# - ASP.NET Core 6 MVC : how to implement layout logic?

c# - 测试类找不到连接字符串

c# - 将 ILogger 或 ILoggerFactory 传递给 AspNet Core 中的构造函数?

c# - 从类型中获取 DbSet

asp.net-mvc - SignalR Asp.net core Web 应用程序中消息未从服务器发送到客户端

asp.net-core - 部署asp.net核心应用程序时如何处理环境差异?

asp.net-core - 如何在ASP.Net Core 1.1MVC中确认电话号码