有没有办法在 .net core 类库中使用 IHostingEnvironment?

3

在我的应用程序中,我将一些图像文件保存到应用程序文件夹中。目前使用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
        }
    }

这个扩展方法在一个类库中,我正在从automapper映射中调用该扩展方法。

我遇到的问题是,我不能在类库中使用IHostingEnvironment,因为它不包含Microsoft.AspNetCore.Hosting.Abstractions.dll程序集。

有没有办法在类库中使用IHostingEnvironment

1个回答

5

在您的类库中使用IHostingEnvironment没有问题。只需要使用以下命令在您的类库中安装其NuGet包:

Install-Package Microsoft.AspNetCore.Hosting

您可以像这样从 DI 容器中解析 IHostingEnvironment

public class SomeClass
{
    private IHostingEnvironment _hostingEnvironment;

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

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

谢谢您的输入,但我该如何引用Microsoft.AspNetCore.Hosting?我在添加引用窗口中找不到它。 - Arunprasanth K V
@ArunprasanthKV 您好,您可以通过 NuGet 简单地安装它:Microsoft.AspNetCore.Hosting。 - Moien Tajik
链接已经失效了。这就是为什么Stack Overflow希望您将代码示例放在答案中而不仅仅是一个链接的原因。 - Kurt
你说得对,答案已经更新并附上了代码示例。@Kurt - Moien Tajik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接