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

Viewed 489

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

1 Answers

First, register HttpcontextAccessor service in Startup.cs,

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.

Related