QuranX Administrator
QuranX Administrator

Reputation: 425

Get wwwroot path when in ConfigureServices (aspnetcore)

In my aspnetcore app (v2.1) I need to configure a read-only database (entityframework core + SQLite) which is in ~/wwwroot/App_Data/quranx.db

I need to call this code in Startup.ConfigureServices

services.AddDbContext<QuranXDataContext>(options => options
    .UseSqlite($"Data Source={databasePath}")
    .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
);

But at that point I cannot find a way to get the path to wwwroot. To get that path I need IHostingEnvironment, but I am unable to get a reference to that until Startup.Configure is called, and that is after Startup.ConfigureServices has finished.

How is this done?

Upvotes: 15

Views: 22366

Answers (2)

Atif
Atif

Reputation: 427

Path.GetFullPath("wwwroot");

Upvotes: 6

Kirk Larkin
Kirk Larkin

Reputation: 93003

It's easy enough to access IHostingEnvironment in ConfigureServices (I've explained how below) but before you read the specifics, take a look at Chris Pratt's warning in the comments about how storing a database in wwwroot is a very bad idea.


You can take a constructor parameter of type IHostingEnviroment in your Startup class and capture that as a field, which you can then use in ConfigureServices:

public class Startup
{
    private readonly IHostingEnvironment _env;

    public Startup(IHostingEnvironment env)
    {
        _env = env;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        // Use _env.WebRootPath here.
    }

    // ...
}

For ASP.NET Core 3.0+, use IWebHostEnvironment instead of IHostingEnvironment.

Upvotes: 33

Related Questions