如何在启动中的ConfigureServices方法中获得开发/登台/生产托管环境?
public void ConfigureServices(IServiceCollection services)
{
// Which environment are we running under?
}
ConfigureServices方法只接受一个IServiceCollection参数。
如何在启动中的ConfigureServices方法中获得开发/登台/生产托管环境?
public void ConfigureServices(IServiceCollection services)
{
// Which environment are we running under?
}
ConfigureServices方法只接受一个IServiceCollection参数。
当前回答
在NET6中,启动和程序合并为一个文件,启动中不再有ConfigureServices方法。现在你可以简单地使用
builder.Environment.IsProduction()
builder.Environment.IsStaging()
builder.Environment.IsDevelopment()
就在第一行之后
var builder = WebApplication.CreateBuilder(args);
其他回答
从ASP开始。NET Core 3.0中,从ConfigureServices和Configure中访问环境变量要简单得多。
只需将IWebHostEnvironment注入到启动构造函数本身。像这样…
public class Startup
{
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
Configuration = configuration;
_env = env;
}
public IConfiguration Configuration { get; }
private readonly IWebHostEnvironment _env;
public void ConfigureServices(IServiceCollection services)
{
if (_env.IsDevelopment())
{
//development
}
}
public void Configure(IApplicationBuilder app)
{
if (_env.IsDevelopment())
{
//development
}
}
}
参考:https://learn.microsoft.com/en - us/aspnet/core/fundamentals/environments?view=aspnetcore - 3.0 # inject-iwebhostenvironment-into-the-startup-class
在NET6中,启动和程序合并为一个文件,启动中不再有ConfigureServices方法。现在你可以简单地使用
builder.Environment.IsProduction()
builder.Environment.IsStaging()
builder.Environment.IsDevelopment()
就在第一行之后
var builder = WebApplication.CreateBuilder(args);
我想在我的服务中加入这种环境。这真的很容易做到!我只是像这样把它注入到构造函数中:
private readonly IHostingEnvironment _hostingEnvironment;
public MyEmailService(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
现在在稍后的代码中,我可以这样做:
if (_hostingEnvironment.IsProduction()) {
// really send the email.
}
else {
// send the email to the test queue.
}
编辑:
上面的代码是用于。net Core 2的。对于版本3,您将使用IWebHostEnvironment。
由于还没有完整的复制和粘贴解决方案,基于Joe Audette的回答:
public IWebHostEnvironment Environment { get; }
public Startup(IWebHostEnvironment environment, IConfiguration configuration)
{
Environment = environment;
...
}
public void ConfigureServices(IServiceCollection services)
{
if (Environment.IsDevelopment())
{
// Do something
}else{
// Do something
}
...
}
以防有人也在看这个。在.net core 3+中,这些都已经过时了。更新方式为:
public void Configure(
IApplicationBuilder app,
IWebHostEnvironment env,
ILogger<Startup> logger)
{
if (env.EnvironmentName == Environments.Development)
{
// logger.LogInformation("In Development environment");
}
}