asp.net-coreasp.net-core-mvc

IHostingEnvironment.WebRootPath is null when using EF7 commands


Problem

When I try to add a migration to my code, e.g: dnx ef migrations add initial,

the env.WebRootPath in Startup(IHostingEnvironment env) is null.

This will give me compilation errors when adding a new migration or updating the database.

The Code

In the Startup.cs class I have these lines in the constructor:

public Startup(IHostingEnvironment env)
{
    // ...
    MyStaticClass.Initialize(env.WebRootPath);
    // ...
    _hostingEnvironment = env;
}

Here env.WebRootPath is null and in the Initialize function this throws an exception.

In the ConfigureServices function of the Startup.cs I resolve my class dependencies:

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddInstance<IMyService>(new MyService(_hostingEnvironment.WebRootPath))
    // Note: _hostingEnvironment is set in the Startup constructor.
    // ...
}

Notes


Solution

  • There is an issue reported on github regarding my problem:

    https://github.com/aspnet/EntityFramework/issues/4494

    I used the workaround in the comments now it seems to be working fine:

    if (string.IsNullOrWhiteSpace(_env.WebRootPath))
    {
       env.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
    }