在我的 Core 1.0 应用程序中,Startup ctor 将几个额外的 json 文件加载到配置中...
public Startup(IHostingEnvironment env) {
Environment = env;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json")
.AddJsonFile($"activityGroups.{env.EnvironmentName}.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
然后在 ConfigureServices 中,我将这些数据从配置中抓取到强类型列表中......
public void ConfigureServices(IServiceCollection services) {
services.AddDbContext<Models.DbContext>(
options => options.UseSqlServer(
Configuration["Data:DefaultConnection:ConnectionString"]
)
);
services.AddScoped<Repository>();
services.AddTransient<DbSeed>();
services.AddOptions();
services.Configure<List<Models.Task>>(Configuration.GetSection("ActivityGroups"));
}
然后,在 Configure 中,强类型列表被注入(inject)并用于 db init..
public void Configure(
IApplicationBuilder app,
DbSeed seed,
ILoggerFactory logging,
IOptions<List<ActivityGroup>> activityGroupConfig
) {
app.UseAuthentication();
app.UseMvc();
bool seedDb;
bool.TryParse(Configuration.GetSection("SeedDb").Value, out seedDb);
if (seedDb) {
seed.EnsureSeeded(activityGroupConfig.Value);
}
}
然而...
In 2.0 projects, move the SeedData.Initialize call to the Main method of Program.cs...
As of 2.0, it's bad practice to do anything in BuildWebHost except build and configure the web host. [configure web host includes data seeding?] Anything that's about running the application should be handled outside of BuildWebHost — typically in the Main method of Program.cs.
https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/#move-database-initialization-code
但是,在"new"Main(string[] args)
中,我们无权访问 dbcontext(直到 Startup.ConfigureServices
)。即使在 MS 文档中的 SeedData.Initialize(services);
调用中,SeedData 将如何访问直到稍后在配置服务中才定义的连接字符串?
The adoption of this new 2.0 pattern is highly recommended and is required for product features like Entity Framework (EF) Core Migrations to work.
https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/#update-main-method-in-programcs
我一直在谷歌搜索和挖掘文档和 samples (例如带有硬编码值的种子)没有清楚地了解期望或推荐的设计(除了,“不要做你以前做过的事”。)
这里有人更熟悉或更有经验如何在 ASP.NET Core 2.0 中从磁盘上的 json 进行数据库播种吗?
最佳答案
因此,在 this SO question 的帮助下,我得到了从 Program.cs 中获取服务的要点
public class Program {
public static void Main(string[] args) {
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
var logger = services.GetRequiredService<ILoggerFactory>();
var ctx = services.GetRequiredService<DataContext>();
// Now I can access the DbContext, create Repository, SeedData, etc!
现在,问题在于试图找出如何从 appsettings.json 访问值,新的 SO 问题 here .
关于c# - 从 ASP.NET Core 2.0 中的 json 文件进行数据库播种的正确位置是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48698498/