Is there a way to use "IWebHostEnvironment" inside static class in ASP Core?
My class :
public class MainHelper
{
private readonly IWebHostEnvironment _hostingEnvironment;
public MainHelper(IWebHostEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public static void SaveFile(IFormFile file)
{
var path = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
using (var fileStream = System.IO.File.Create(Path.Combine(path, file.FileName)))
{
file.CopyTo(fileStream);
}
}
}
I have error in line:
var path = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
Error: c# session an object reference is required for the non-static field method or property 'MainHelper._hostingEnvironment'
Please Advise
Maybe something like that can help you:
It this sample you should call
MainHelper.Initialize
with yourIWebHostEnvironment
instance at yourStartup.cs
, etc. instead calling constructor. In this sample you can initializeMainHelper
just once. (Not tested)