How do I use the IHostingEnvironment
interface without initiating it in a constructor?
my Startup.cs:
public Startup(IHostingEnvironmen
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.