【问题标题】:Is there any way to use IHostingEnvironment in .net core class library?有什么方法可以在 .net 核心类库中使用 IHostingEnvironment 吗?
【发布时间】:2019-01-10 05:51:54
【问题描述】:

在我的应用程序中,我将一些图像文件保存到应用程序文件夹本身。当前使用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 Mapping 调用这个扩展方法。

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

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

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc asp.net-core-2.1


    【解决方案1】:

    在你的类库中使用IHostingEnvironment没有问题。只需在类库中使用此命令安装其 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.
        }
    }
    

    【讨论】:

    • 感谢您的输入,但我如何参考 Microsoft.AspNetCore.Hosting,我在添加参考窗口中找不到它
    • @ArunprasanthKV 欢迎您,只需通过 NuGet 安装它:Microsoft.AspNetCore.Hosting
    • 链接失效了。这就是为什么 Stack Overflow 希望您将代码示例放在答案中,而不仅仅是一个链接。
    • 没错,答案已更新为代码示例。 @库尔特
    猜你喜欢
    • 2017-11-01
    • 2019-11-05
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多