Search code examples
c#class.net-coredependency-injectionstatic-classes

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

  • Maybe something like that can help you:

    public static class MainHelper
    {
        private static IWebHostEnvironment _hostingEnvironment;
    
        public static bool IsInitialized { get; private set; }
    
        public static void Initialize(IWebHostEnvironment hostEnvironment)
        {
            if(IsInitialized)
                throw new InvalidOperationException("Object already initialized");
            
            _hostingEnvironment = hostEnvironment;
            IsInitialized = true;
        }
    
        public static void SaveFile(IFormFile file)
        {
            if(!IsInitialized)
                throw new InvalidOperationException("Object is not initialized");
    
            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);
            }
        }
    }
    

    It this sample you should call MainHelper.Initialize with your IWebHostEnvironment instance at your Startup.cs, etc. instead calling constructor. In this sample you can initialize MainHelper just once. (Not tested)