Search code examples
asp.net-coreasp.net-core-mvcasp.net-core-2.1

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


In my application I am saving some image files into the application folder itself. Currently using IHostingEnvironment interface for getting the Path. like

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

for getting path using this code _hostingEnvironment.ContentRootPath

But in future we may change the image location to cloud or some other places, so I have written an extension method for getting the actual path

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

This extension method is there in a class library and I am calling this extension method from automapper Mapping .

The issue I am facing is I cannot use IHostingEnvironment in class library because of it does not contain Microsoft.AspNetCore.Hosting.Abstractions.dll assembly.

Is there any way to use IHostingEnvironment in the class library ?


Solution

  • There is no problem to use IHostingEnvironment in your class library. Simply install its NuGet package using this command in your class library:

    Install-Package Microsoft.AspNetCore.Hosting
    

    And resolve IHostingEnviroment from your DI Container like this:

    public class SomeClass
    {
        private IHostingEnvironment _hostingEnvironment;
    
        public SomeClass(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }
    
        public void SomeMethod()
        {
            // Use IHostingEnvironment with _hostingEnvironment here.
        }
    }