简体   繁体   English

如何在 OnModelCreating() 中获取环境变量?

[英]How to get environment variable in OnModelCreating()?

I'm calling a method in OnModelCreating() in DbContext.我在 DbContext 的 OnModelCreating() 中调用一个方法。 I do not want it to be called in every environment.我不希望在每个环境中都调用它。

Saw this question on stackoverflow . 在 stackoverflow 上看到这个问题

Tried to implement it like this.试图像这样实现它。 OnModelCreating() in DbContext implementation. DbContext 实现中的 OnModelCreating()。

  var env = this.GetService<IWebHostEnvironment>();
  if (env.EnvironmentName == "Development")
  {
      modelBuilder.SeedData();
  }

In Program.cs在 Program.cs 中

 services
            .AddDbContext<TDbContext>((serviceProvider, options) => options.UseSqlServer(configuration.GetConnectionString(connectionStringName))
            .UseInternalServiceProvider()
            .AddInterceptors(serviceProvider.GetRequiredService<SOMESERVICE>()));

UseInternalServiceProvider() is not recognized and I get compile-time error. UseInternalServiceProvider() 无法识别,我收到编译时错误。 I'm using .net 6 and maybe, question I linked used an old version.我正在使用 .net 6 也许,我链接的问题使用了旧版本。

UPDATE: Tried更新:试过

Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")

But it returns null但它返回 null

In.net core 6 I used like this, the app is the app=builder.build();在.net core 6 我是这样用的,app是app=builder.build(); in Program.cs在 Program.cs 中

if (app.Environment.IsDevelopment()) {如果(app.Environment.IsDevelopment()){

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM