如何在 ASP Core 中的 static class 中使用 "IWebHostEnvironment"

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

有没有办法在 ASP Core 的静态 class 中使用“IWebHostEnvironment”?

我的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);
            }
    }
}

我有一行错误:

var path = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");

错误: c# 会话非静态字段方法需要对象引用或属性 'MainHelper._hostingEnvironment'

请指教

也许类似的东西可以帮助你:

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);
        }
    }
}

在这个示例中,您应该使用 Startup.cs 中的 IWebHostEnvironment 实例调用 MainHelper.Initialize,等等,而不是调用构造函数。在此示例中,您可以只初始化 MainHelper 一次。 (未测试)

因为接受的答案是一个。 但是万一有人提到在静态 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>();
            }
        }

用法:

var path = Common.WebEnv().WebRootPath;
   var environment = app.ApplicationServices
                .CreateScope()
                .ServiceProvider
                .GetRequiredService<IWebHostEnvironment>();