まず:デフォルトを使用Program.csが、それはすでにあなたのための設定を追加します。
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
第二に、あなたのクラスのためのインタフェースを作成し、Iconfiguration
フィールドを作成することにより、依存性注入で設定を渡す:
private readonly IConfiguration Configuration;
その後、コンストラクタで渡す:
public Test(IConfiguration configuration)
{
Configuration = configuration;
}
をそうDependency Injection
を使用するためには、あなたのクラスのためのインタフェースを作成します。それにIConfiguration
を渡す必要なくインスタンスを作成することができます
ここにクラスとインターフェイスはあります:
using Microsoft.Extensions.Configuration;
namespace GetUserIdAsyncNullExample
{
public interface ITest
{
void Method();
}
public class Test : ITest
{
public Test(IConfiguration configuration)
{
Configuration = configuration;
}
private readonly IConfiguration Configuration;
public void Method()
{
string here = Configuration["placeto:login"];
}
}
}
は、その後、あなたのstartup.csに呼び出すことによって、あなたのクラスのDependency Injection
を実装:あなたのConfigureServices
方法
で
services.AddSingleton< ITest, Test>();
を今すぐあなたもDependency Injection
で使用するすべてのクラスにクラスのインスタンスを渡すことができ
たとえば、あなたがExampleController
にあなたのクラスを使用したい場合は、次のようにしてください:
private readonly ITest _test;
public ExampleController(
ITest test
)
{
_test = test;
}
これで、コントローラの任意の場所にアクセスするための_testインスタンスが作成されました。
https://stackoverflow.com/questions/46632090/mvc-core-2-0-how-to-use-an-appsettings-json-file-via-configuration/46632521#46632521 – anserk
の可能な複製MSからそれを説明する方法=> https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration?tabs=basicconfiguration – CodeNotFound
しかし、私はカスタムクラスで読み込む必要があります、例はコントローラにあり、私は避難所ですいくつかのオプションを試しました。 .Net標準で使用されています。文字列userName = System.Configuration.ConfigurationManager.AppSettings ["PFUserName"]; '.Netコアの読み込みweb.configのために等価です@CodeNotFound –