2016-08-05 7 views
0

EF7でSQLiteとの相対接続文字列を使用できないため、ConfigureServicesルーチン中にStartup.cs内からアプリケーションディレクトリを取得する方法が必要です.DBContextが構成されています。Startup.CsのConfigureメソッド内からアプリケーションディレクトリを取得

どのように.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); 
... 
} 
関連する問題