当您使用 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/