在EF7上不能使用SQLite的相對連接字符串,所以我需要一種方法在ConfigureServices例程中從Startup.cs中獲取應用程序目錄,其中DBContext已配置。從啓動中的Configure方法中獲取應用程序目錄.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"));
});
}
工作非常好,我喜歡這種方法。 我完全錯過了構造函數中的IHostingEnvironment。感謝您指出了這一點。 –
我不明白這是如何工作的,ConfigureServices()在Startup()之前運行,所以當從ConfigureServices訪問時環境變量不會總是空的? –
不應該首先調用Startup構造函數,startup不是靜態類,在調用構造函數創建Startup實例之前,不能調用ConfigureServices,因爲它是一種實例方法而不是靜態方法。它確實在2.0項目模板中有所改變,現在IConfiguration在Program中被創建並被傳遞到Startup構造函數,儘管舊的語法仍然可以工作。 –