Home > database >  .AddRazorRuntimeCompilation() results in The type or namespace name 'IWebHostEnvironment'
.AddRazorRuntimeCompilation() results in The type or namespace name 'IWebHostEnvironment'

Time:07-23

In a .NET 6 / ASP.NET Core app after adding the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation Nuget package and adding

builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();

I get this error, when opening a view:

The type or namespace name 'IWebHostEnvironment' could not be found (are you missing a using directive or an assembly reference?)

                Write(__tagHelperExecutionContext.Output);
                __tagHelperExecutionContext = __tagHelperScopeManager.End();
                WriteLiteral("\n\n</html>\n");
            }
            #pragma warning restore 1998
            [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]

            public IWebHostEnvironment HostingEnv { get; private set; }

            [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
            public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
            [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
            public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
            [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
            public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }

IWebHostEnvironment is referenced in _Layout.cshtml:


@inject IWebHostEnvironment HostingEnv
<!DOCTYPE html>
<html lang="en">
...
</html>

Note:

The accepted answer works, however, Rider (and maybe ReSharper) might mark Microsoft.AspNetCore.Hosting. in the @inject statement as redundant.

I don't know why this happens, but I added this above the @inject statement line:

@* ReSharper disable once RedundantNameQualifier *@

Also, read my comment regarding the IsDevelopment() error I got after using the full qualified reference.

CodePudding user response:

Have you tried fully qualifying the namespace and making it

@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment HostingEnv

If that works then I recall there being a difference in how _ViewImports files are processed during runtime compilation versus standard, it doesn’t cascade the same way. You may therefore find that your existing _ViewImports files aren’t all being read.

  • Related