简体   繁体   English

ASP.NET 核心3.1:添加框架服务:IHostEnvironment

[英]ASP.NET Core 3.1: Add framework service: IHostEnvironment

I have an asp.net core 3.1 application and I'm trying to inject the framework service IHostEnvironment in my ConfigureServices so I can get the environment in my application service and the application is throwing an error.我有一个 asp.net 核心 3.1 应用程序,我试图在我的 ConfigureServices 中注入框架服务 IHostEnvironment,这样我就可以在我的应用程序服务中获取环境,并且应用程序抛出错误。

Startup.cs:启动.cs:

private IHostEnvironment _env;
public Startup(IConfiguration configuration, IHostEnvironment hostEnvironment)
{
Configuration = configuration;
_env = hostEnvironment;
}

public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
//add framework services
services.AddSingleton<IHostEnvironment>(_env);

//add application services
services.AddSingleton<IMySvc, MySvc>();

}

MySvc.cs MySvc.cs

public class MySvc : IMySvc
{
private IConfigurationRoot _config;
//private IHostingEnvironment _env;
private IHostEnvironment _env;

public string Env{
get{
if(_env.IsDevelopment()){return _config["MyConfiguration: MyProperty"];}
}
}
public HttpSvc(IConfigurationRoot config, IHostEnvironment env)
{
_config = config;
_env = env;
}

}

The application fails to run complaining about some services not being able to be constructed.应用程序无法运行,抱怨某些服务无法构建。

As mentioned in the migration guide from 2.2 to 3.0 IWebHostEnvironment should be injected in the Startup class instead of IHostingEnvironment .正如从 2.2 到 3.0 的迁移指南中提到的, IWebHostEnvironment应该注入Startup class 而不是IHostingEnvironment Also I would suggest to consider injecting IConfiguration into service instead of IConfigurationRoot or even better consider to bind/register relevant config parts to some class and inject it (see Configuration in ASP.NET Core and Options pattern in ASP.NET Core )此外,我建议考虑将IConfiguration注入服务而不是IConfigurationRoot ,或者甚至更好地考虑将相关配置部分绑定/注册到某些 class 并注入它(请参阅ASP.NET Core 中的配置和 ASP.NET Core 中的选项模式

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

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