[英]Safely create new instance of EF Core DbContext
有時在 .NET Core 中,有時需要多個DbContext
(並行數據庫請求等)。
在我的 DbContext class 中使用這兩種解決方案中的任何一種是否安全?
private static string _connectionString;
private static string ConnectionString =>
_connectionString ??= new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build().GetConnectionString("CoreConnection");
public static CoreContext GetContext()
{
var options = new DbContextOptionsBuilder<CoreContext>()
.UseNpgsql(ConnectionString)
.Options;
return new CoreContext(options);
}
或者
private static IConfiguration _configuration;
private static IConfiguration Configuration =>
_configuration ??= new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
private static string ConnectionString =>
Configuration.GetConnectionString("CoreConnection");
public static CoreContext GetContext()
{
var options = new DbContextOptionsBuilder<CoreContext>()
.UseNpgsql(ConnectionString)
.Options;
return new CoreContext(options);
}
我已經閱讀(對於舊的 ASP .NET),您應該避免在應用程序 memory 中以純文本形式保留敏感數據,例如密碼和包含密碼的連接字符串,因為 memory 可能在崩潰后被黑客入侵或轉儲/保存。
.NET Core 仍然如此嗎? (猜應該是)
使用IConfiguration
是否更安全,還是將連接字符串以純文本形式存儲在 memory 中?
網絡核心中可與DI一起使用的全局IConfiguration
是否存儲了appsettings.json
中的所有appsettings.json文件數據?
memory 是否更有可能被黑客入侵,然后黑客可能能夠直接讀取appsettings.json
信息?
我認為這可能會有所幫助。
使用后處理 DbContext 非常重要。 這可以確保釋放任何非托管資源,並取消注冊任何事件或其他掛鈎,以防止 memory 泄漏,以防實例仍然被引用。 DbContext 不是線程安全的。 不要在線程之間共享上下文。 確保在繼續使用上下文實例之前等待所有異步調用。 EF Core 代碼拋出的 InvalidOperationException 可以將上下文放入不可恢復的 state。 此類異常表示程序錯誤,並非旨在從中恢復。
https://docs.microsoft.com/en-us/ef/core/dbcontext-configuration/
這也可以幫助:
切勿在源代碼中存儲密碼或其他敏感數據。
https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-5.0&tabs=windows
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.