You should use the integrated dependency injection because it makes your code decoupled and easier to change without disrupting work and making it easier to unit test.
If you want to access it through a static class or method, then your code will be difficult to test, as in unit test, it will always use the path to the project, and not some specific line for testing.
The way you described it is absolutely correct, and NOT wrong! The following is just a 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 env is null in the constructor, you may need to register it yourself in Startup.cs if ASP.NET Core does not already do this:
services.AddSingleton<IHostingEnvironment>(env);
where env is the instance passed to the Startup constructor.
Tseng source share