Ryan Mann
Ryan Mann

Reputation: 5357

Get Application Directory from within Configure method in Startup.Cs

You can't use a relative connection string with SQLite on EF7, so I need a way to get the application Directory from within Startup.cs during the ConfigureServices Routine where the DBContext is configured.

Any idea how to do this with the .NetCoreApp Libraries?

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();

        //Figure out app directory here and replace token in connection string with app directory.......    

        var connectionString = Configuration["SqliteConnectionString"];

        if (string.IsNullOrEmpty(connectionString))
            throw new Exception("appSettings.json is missing the SqliteConnectionString entry.");
        services.AddDbContext<MyContext>(options =>
        {
            options.UseSqlite(connectionString, b => b.MigrationsAssembly("xyz.myproject.webapp"));

        });
    }

Upvotes: 1

Views: 2930

Answers (4)

jjs
jjs

Reputation: 11

For a Function App, grabbing the context from the IFunctionsHostBuilder object and then accessing the ApplicationRootPath worked for me:

public class ContainerConfig : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        var context = builder.GetContext();

        ConfigureAppSettings(builder.Services, context);

        ...
    }

    public void ConfigureAppSettings(IServiceCollection services, FunctionsHostBuilderContext context)
    {
        ...

        var config = new ConfigurationBuilder()
            .SetBasePath(context.ApplicationRootPath)
            ...
    }
}

Upvotes: 1

user2496205
user2496205

Reputation: 1

Just use dependency injection where you need to get the path.

Example

ValueController(..., IHostingEnvironment env)
{
Console.WriteLine(env.ContentRootPath);
...
}

Upvotes: 0

Joe Audette
Joe Audette

Reputation: 36736

you can stash the environment in a local property and then you can access it to get the base path like this:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);


    Configuration = builder.Build();

    environment = env;
}

public IHostingEnvironment environment { get; set; }
public IConfigurationRoot Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    // you can access environment.ContentRootPath here
}

Upvotes: 8

Ignas
Ignas

Reputation: 4338

You can get the application base directory using following:

AppContext.BaseDirectory;

Upvotes: 5

Related Questions