私はappsettings.json
ファイルをWebプロジェクトに設定する方法を知っています。しかし、クラスライブラリプロジェクトからアクセスする方法を教えてください。クラスライブラリプロジェクトからappsettings.jsonファイル設定にアクセス
ウェブプロジェクトで以下のように設定できます。クラスライブラリプロジェクトからその値にアクセスするにはどうすればよいですか?それは可能ですか?
あなたが次にあなたがHomeController
の値またはこれを注入し、他の場所を取得するセクションを取得し、それをバインドし、
// Add our Config object so it can be injected
services.Configure<MyConfig>(option => Configuration.GetSection("MyConfig").Bind(option));
TOこの
// Add our Config object so it can be injected
services.Configure<MyConfig>(Configuration);
を変更する必要が
public class MyConfig
{
public string ApplicationName { get; set; }
public int Version { get; set; }
}
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
Configuration = builder.Build();
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<MyConfig>(Configuration);
}
public class HomeController : Controller
{
private readonly IOptions<MyConfig> config;
public HomeController(IOptions<MyConfig> config)
{
this.config = config;
}
// GET: /<controller>/
public IActionResult Index() => View(config.Value);
}
の
ConfigureServices
方法でそれを登録して、あなたは別のプロジェクトのクラスファイルにそれを注入する方法を私を見ることができますか?はい、私たちはあなたが示しているようにWebプロジェクト内でそれを行うことができます。しかし、私は別のクラスライブラリプロジェクトでそれをどうやって行うことができますか?私は複数のクラスライブラリプロジェクトを持っている同じソリューションの下で。 – Sampath例を追加してください。 – Ahmar
@Ahmar ... IOptions config;でICategoryインターフェイス - エラー...インターフェイスにフィールドを含めることはできません –
dinotom