.net.net-5library-projectserver.mappath

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.


Solution

  • 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.