Home > Net >  ASP.NET Core 3.1: Add framework service: IHostEnvironment
ASP.NET Core 3.1: Add framework service: IHostEnvironment

Time:12-06

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.

Startup.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

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.

CodePudding user response:

As mentioned in the migration guide from 2.2 to 3.0 IWebHostEnvironment should be injected in the Startup class instead of 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 )

  • Related