Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a reference to IWebHostEnvironment inside a library project? (Also inside static class :()

I need to use Server.MapPath. Since library projects does not have Startup.cs i cannot apply the normal way.

like image 567
heimzza Avatar asked Sep 19 '25 03:09

heimzza


2 Answers

First, register HttpcontextAccessor service in Startup.cs of the project which uses the Library project,

services.AddHttpContextAccessor();

then in the class,

private static HttpContext _httpContext => new HttpContextAccessor().HttpContext;
private static IWebHostEnvironment _env => (IWebHostEnvironment)_httpContext.RequestServices.GetService(typeof(IWebHostEnvironment));

now you can access it in a static class and a static method.

This did the trick for me. If anyone needs.

like image 112
heimzza Avatar answered Sep 21 '25 02:09

heimzza


Another possible solution in .NET 6.0 is as follows:

public static class MainHelper
{
    public 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;
    }
}

Register HttpcontextAccessor and send parameters to Initialize in Program.cs

builder.Services.AddHttpContextAccessor();
MainHelper.Initialize(builder.Environment);

Now you can use _hostingEnvironment in any where in your project like following:

var path = MainHelper._hostingEnvironment.ContentRootPath;

or

var path = MainHelper._hostingEnvironment.WebRootPath;
like image 24
Adeel Ahmed Avatar answered Sep 21 '25 04:09

Adeel Ahmed