简体   繁体   中英

How to get environment variable in OnModelCreating()?

I'm calling a method in OnModelCreating() in DbContext. I do not want it to be called in every environment.

Saw this question on stackoverflow .

Tried to implement it like this. OnModelCreating() in DbContext implementation.

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

In 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. I'm using .net 6 and maybe, question I linked used an old version.

UPDATE: Tried

Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")

But it returns null

In.net core 6 I used like this, the app is the app=builder.build(); in Program.cs

if (app.Environment.IsDevelopment()) {

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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