有没有办法在 .net 核心 class 库中使用 IHostingEnvironment?

Is there any way to use IHostingEnvironment in .net core class library?

在我的应用程序中,我将一些图像文件保存到应用程序文件夹本身。当前使用 IHostingEnvironment 接口获取路径。 喜欢

private readonly IHostingEnvironment _hostingEnvironment;
        /// <summary>
        /// Initializes a new instance of the <see cref="ProductController"/> class.
        /// </summary>
        /// <param name="unitService">The product service.</param>
        public ProductController(IProductService productService, IHostingEnvironment hostingEnvironment)
        {
            this._productService = productService;
            this._hostingEnvironment = hostingEnvironment;
        }

使用此代码获取路径_hostingEnvironment.ContentRootPath

但是以后我们可能会把图片位置改到云端或者其他地方,所以我写了一个获取实际路径的扩展方法

public static class AssetPathHandlerExtensions
    {
        private readonly IHostingEnvironment _hostingEnvironment;//error

        public static string AppendAssetPath(this string fileName, string subDirectryPath)
        {
           //here i need to get the ContentRootPath and append it with filename
        }
    }

此扩展方法位于 class 库中,我从 automapper 映射调用此扩展方法。

我面临的问题是我无法在 class 库中使用 IHostingEnvironment,因为它不包含 Microsoft.AspNetCore.Hosting.Abstractions.dll 程序集。

有什么方法可以在 class 库中使用 IHostingEnvironment 吗?

在您的 class 库中使用 IHostingEnvironment 没有问题。只需在 class 库中使用此命令安装其 NuGet 包:

Install-Package Microsoft.AspNetCore.Hosting

并像这样从您的 DI 容器中解析 IHostingEnviroment

public class SomeClass
{
    private IHostingEnvironment _hostingEnvironment;

    public SomeClass(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    public void SomeMethod()
    {
        // Use IHostingEnvironment with _hostingEnvironment here.
    }
}