heimzza
heimzza

Reputation: 286

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.

Upvotes: 4

Views: 2638

Answers (3)

Mohammad Taheri
Mohammad Taheri

Reputation: 474

I had the same problem. It was easy to solve.

Since I was using Clean Architecture with dotnet 8, I needed some Asp.Net features like IFormFile and IWebHostEnvironment in a separate class library.

In past, we could use some packages to have access to them but they are all deprecated now.

Reason:Based on Microsoft docs:

With the release of .NET Core 3.0, many ASP.NET Core assemblies are no longer published to NuGet as packages.

Solution:

The solution is too easy, Just follow these steps:

1- Go to your class libray and open the csproj file

2- Add this:

 <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
 </ItemGroup>

Your completed csproj file must be something like this:

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
    </PropertyGroup>

    <ItemGroup>
        <FrameworkReference Include="Microsoft.AspNetCore.App" />
    </ItemGroup>    

</Project>

Upvotes: 0

heimzza
heimzza

Reputation: 286

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.

Upvotes: 5

Adeel Ahmed
Adeel Ahmed

Reputation: 345

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;

Upvotes: 1

Related Questions