从Startup.Cs中的Configure方法中获取应用程序目录

Rya*_*ann 0 c# asp.net-core

您不能在EF7上使用与SQLite的相对连接字符串,因此我需要一种方法在配置DBContext的ConfigureServices Routine期间从Startup.cs中获取应用程序目录.

知道如何使用.NetCoreApp库做到这一点吗?

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

        });
    }
Run Code Online (Sandbox Code Playgroud)

Joe*_*tte 6

您可以将环境存储在本地属性中,然后您可以访问它以获取如下所示的基本路径:

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
}
Run Code Online (Sandbox Code Playgroud)


Ign*_*nas 5

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

AppContext.BaseDirectory;
Run Code Online (Sandbox Code Playgroud)