简体   繁体   中英

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"));

        });
    }

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
}

您可以使用以下命令获取应用程序基本目录:

AppContext.BaseDirectory;

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

Example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM