How do I use the IHostingEnvironment
interface without initiating it in a constructor?
my Startup.cs:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
Configuration = builder.Build();
}
My Class:
public class FileReader
{
// I don't want to initiate within a constructor
public string ReadFile(string fileName)
{
// this is wrong! how can I use it?
var filename = Path.Combine(IHostingEnvironment.WebRootPath, fileName);
}
}
What is the purpose of IHostingEnvironment interface in ASP.NET Core? Provides information about the web hosting environment an application is running in. In ASP.NET Core 3.0, IHostingEnvironment interfaces is marked obsolete. You can still use them, but you'll get warnings at build time.
IWebHostEnvironment Provides information about the web hosting environment an application is running in. belongs to namespace Microsoft.AspNetCore.Hosting. The IWebHostEnvironment interface need to be injected as dependency in the Controller and then later used throughout the Controller.
WebRootPath is the base path for all the static files served by the application, such as CSS, JavaScript or Image files. It is actually a sub path of the ContentRootPath.
You should use the integrated dependency injection as it makes your code decoupled and easier to change without breaking stuff and make it very easy to unit test.
If you would access it via static class or method, then your code becomes hard to test as in unit test it would always use the project path and not some specific string for testing.
The way you described it absolutely correct and it's NOT wrong! Below just the complete example.
public class FileReader
{
private readonly IHostingEnvironment env;
public FileReader(IHostingEnvironment env)
{
if(env==null)
throw new ArgumentNullException(nameof(env));
this.env = env;
}
public string ReadFile(string fileName)
{
var filename = Path.Combine(env.WebRootPath, fileName);
}
}
If the env
value is null
in the constructor, you may need to register it yourself in Startup.cs
, if ASP.NET Core doesn't do it already:
services.AddSingleton<IHostingEnvironment>(env);
where env is the instance passed to the Startup
constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With