I need to use Server.MapPath. Since library projects does not have Startup.cs i cannot apply the normal way.
How do I get a reference to IWebHostEnvironment inside a library project? (Also inside static class :()
1.5k Views Asked by heimzza At
2
There are 2 best solutions below
0

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;
First, register HttpcontextAccessor service in Startup.cs of the project which uses the Library project,
then in the class,
now you can access it in a static class and a static method.
This did the trick for me. If anyone needs.