.Net Core 2.1で構成をセットアップしてアクセスするさまざまな方法と、推奨されていると思われるオプションパターンに関するドキュメントを読みました(https://docs.microsoft.com/en-us/aspnet/core/fundamentals / configuration / options?view = aspnetcore-2.1)。しかし、私は自分が働きたいものを手に入れることができないようです:
私は次のことをしました:
AppSettings:
{
"ConnectionStrings": {
"DefaultConnStr": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=true",
"AW2012ConnStr": "Server=localhost;Database=AW2012;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=true"
}
}
MyConfig:
public class MyConfig
{
public string AWConnStr { get; }
public string DefaultConnStr { get; }
}
起動:
public class Startup
{
public IConfiguration _config { get; set; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
_config = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
//add config to services for dependency injection
//services.AddTransient<IMyConfig, MyConfig>();
//services.AddScoped<IMyConfig, MyConfig>();
var section = _config.GetSection("ConnectionStrings");
services.Configure<MyConfig>(section);
}
private static void HandleGetData(IApplicationBuilder app)
{
//DataHelper dataHelper = new DataHelper(_dataHelper);
var _dataHelper = app.ApplicationServices.GetService<DataHelper>();
app.Run(async context =>
{
//await context.Response.WriteAsync("<b>Get Data</b>");
//await context.Response.WriteAsync(dataHelper.GetCompetitions(context.Request.QueryString.ToString()));
await context.Response.WriteAsync(_dataHelper.GetCompetitions(context.Request.QueryString.ToString()));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Map("/Route1", HandleRoute1);
app.Map("/Route2", HandleRoute2);
app.Map("/GetData", HandleGetData);
app.Run(async (context) =>
{
await context.Response.WriteAsync("Non Mapped Default");
});
}
}
次に、コード内の任意のクラスの構成にアクセスしたいと思います。たとえば、次のクラスがあり、構成情報を読みたいだけです。
public interface IDataHelper
{
string GetCompetitions(string val);
}
public class DataHelper : IDataHelper
{
private readonly MyConfig _settings;
public DataHelper(IOptions<MyConfig> options)
{
_settings = options.Value;
}
public string GetCompetitions( string queryStringVals)
{
return _settings.AWConnStr;
}
}
上記のStartupクラスで示したように、スタートアップのHandleGetData関数で何かにアクセス/呼び出したいので、次のルートを参照すると、http:// localhost:xxxxx / getdata何かから応答が返されます。 .GetData関数。
これは正しいです?私が抱えている問題は、Somethingクラスのインスタンスを作成するときに、構成オブジェクトを渡す必要があるということですが、それを注入する目的を損なうものではありません。DBContextが構成オプションでコンテキストを注入する方法と同様に機能するようにこれを設定するにはどうすればよいですか。そして、services.AddTransientとservices.AddScopedの違いは何ですか?私は両方ともサービスを登録する方法として見ました。
.Net CoreアプリケーションでIConfiguration
は、のインスタンスをコントローラーや他のクラスに渡してはいけません。IOtions<T>
代わりに、強く型付けされた設定を使用する必要があります。これをケースに適用して、MyConfigクラスを変更します(プロパティ名もconfig内の名前と一致する必要があるため、configの名前を変更する必要があります(DefaultConnection-> DefaultConnStr、AW2012ConnStr-> AWConnStr、またはその逆)。
public class MyConfig
{
public string AWConnStr { get; set; }
public string DefaultConnStr { get; set; }
}
登録する:
public void ConfigureServices(IServiceCollection services)
{
// in case config properties specified at root level of config file
// services.Configure<MyConfig>(Configuration);
// in case there are in some section (seems to be your case)
var section = Configuration.GetSection("ConnectionStrings");
services.Configure<MyConfig>(section);
}
必要なサービスにそれを注入します:
public class MyService
{
private readonly MyConfig _settings;
public MyService(IOptions<MyConfig> options)
{
_settings = options.Value;
}
}
そして、services.AddTransientとservices.AddScopedの違いは何ですか?私は両方ともサービスを登録する方法として見ました。
一時的なライフタイムサービスは、要求されるたびに作成されます。
スコープ付きライフタイムサービスは、リクエストごとに1回作成されます。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加