2016-08-05 89 views
0

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

     }); 
    } 

回答

4

,你可以在當地財產藏匿的環境,那麼你就可以訪問它來獲得這樣的基本路徑:

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 
} 
+0

工作非常好,我喜歡這種方法。 我完全錯過了構造函數中的IHostingEnvironment。感謝您指出了這一點。 –

+0

我不明白這是如何工作的,ConfigureServices()在Startup()之前運行,所以當從ConfigureServices訪問時環境變量不會總是空的? –

+0

不應該首先調用Startup構造函數,startup不是靜態類,在調用構造函數創建Startup實例之前,不能調用ConfigureServices,因爲它是一種實例方法而不是靜態方法。它確實在2.0項目模板中有所改變,現在IConfiguration在Program中被創建並被傳遞到Startup構造函數,儘管舊的語法仍然可以工作。 –

1

您可以通過以下獲得應用程序的根目錄:

AppContext.BaseDirectory; 
0

只需使用依賴注入,您需要獲取路徑。

ValueController(..., IHostingEnvironment env) 
{ 
Console.WriteLine(env.ContentRootPath); 
... 
} 
相關問題