[英].Net Core 3-tier architecture passing connection string from presentation layer to data layer issue
我有3層架構的Web API,如下所示:
PresentationLayer(在表示層中,我有appsetting.json,其中的連接字符串在其中)
BusinessLayer(類庫)
DataLayer(類庫)
當我仍在使用.Net Framework時,我曾在dataLayer中執行以下鏈接中所示的代碼,以從表示層的web.config獲取連接字符串:
現在,我正在嘗試使用.Net Core 2.1,並且已經在數據層中構建了相同的類,但是它無法正常工作。 如何最有效地將連接字符串從表示層傳遞到數據層。 在使用.Net框架時,是否曾經有過類似的方式來傳遞連接字符串?
你能幫我嗎。
如何最有效地將連接字符串從表示層傳遞到數據層。 在使用.Net框架時,是否曾經有過類似的方式來傳遞連接字符串?
在Asp.Net Core中,通過依賴注入將連接傳遞到DbConnection
會容易得多。
更改DbConnection
以接受connection string
public class DbConnection { public DbConnection(string connectionString) { _sqlConnection = new SqlConnection(connectionString); }
在PresentationLayer
注冊DbConnection
services.AddTransient<DbConnection>(serviceProvider => new DbConnection(Configuration.GetConnectionString("DefaultConnection")));
創建AppSettings類
public static class AppSettings
{
public static string ConnectionString { get; set; }
}
在Startup.cs中
public Startup(IConfiguration configuration)
{
Configuration = configuration;
BuildAppSettingsProvider();
}
public IConfiguration Configuration { get; }
private void BuildAppSettingsProvider()
{
AppSettings.ConnectionString = Configuration["ConnectionString"];
}
現在,您可以在表示層中訪問AppSettings。
100%有效。
當您有多個圖層時,您很可能正在使用IOC容器。 在數據層中創建一個接口,並在視圖層中執行該實現,然后在IOC容器中注冊並獲取它。 如果您不能直接在SqlConnection中傳遞它,這是最干凈的方法。
有(最少)3個選項。 我認為最好的方法是使用IoC容器。 也許您更喜歡將appconfig文件添加到數據庫層並訪問它以進行層特定設置。 或者,您可以使用默認注入機制將IConfiguration傳遞給業務層,然后通過ctor將其傳遞給DataLayer。
例如
/* ----- Startup.cs ----- */
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IxxxService, xxxBusinessService>();
}
/* ----- UI Layer ----- */
public xxxController(IxxxService xxxBusinessService)
{
this.xxxBusinessService = xxxBusinessService;
}
/* ----- BUSINESS LAYER ----- */
/*
UI/controller knows Business service and IConfiguration objects, and default
injector automatically creates/passes configuration object via ctor to Business layer.
*/
public xxxService(IConfiguration configuration)
{
this.xxxRepository = new xxxRepository(configuration);
}
/* ----- DATA LAYER ----- */
public class xxxRepository: BaseRepository, IxxxRepository
{
public xxxRepository(IConfiguration configuration)
: base(configuration)
{
}
}
public class BaseRepository{
protected xxxDbContext context;
public BaseRepository(IConfiguration configuration)
{
var optionsBuilder = new DbContextOptionsBuilder<xxxDbContext>();
optionsBuilder.UseSqlServer(configuration.GetSection("ConnectionString")["DefaultConnection"]);
this.context = new xxxDbContext(optionsBuilder.Options);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.