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

1.5k Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

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;