'How to use "IWebHostEnvironment" inside static class in ASP Core

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



Solution 1:[1]

As the accepted answer was one. But in case anyone refers using without intialization in static class:

    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.DependencyInjection;

    public class Common{
          public static IWebHostEnvironment WebEnv()
            {
                var _accessor = new HttpContextAccessor();
                return _accessor.HttpContext.RequestServices.GetRequiredService<IWebHostEnvironment>();
            }
        }

Usage:

var path = Common.WebEnv().WebRootPath;

Solution 2:[2]

   var environment = app.ApplicationServices
                .CreateScope()
                .ServiceProvider
                .GetRequiredService<IWebHostEnvironment>();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sambath999
Solution 2 J S