![](/img/trans.png)
[英]How to pass in settings into a class (derived ASP.NET Core Startup.cs) from ConfigureServices in a test
[英]How to pass connection string to UnitOfWork project from startup.cs asp.net core
我在AppDbContext
創建了構造函數,並且上下文是在UnitofWork
中實現的,該實現將字符串傳遞給上下文,但是當我注冊unitofwork
時如何將連接字符串傳遞給startup.cs 。 Repository
和UnitOfWork
在不同的項目中
以下是我的代碼,
構造函數的連接字符串
private readonly string _connection;
public AppDbContext(string connection)
{
_connection=connection;
}
UnitOfWork構造函數
public UnitOfWork(string connection)
{
_context = new AppDbContext(connection);
}
在StartUp.cs中 ,我可以通過下面的連接字符串,從appsettings.json中讀取嗎?
services.AddTransient<IUnitOfWork, UnitOfWork>();
不要那樣做 如果已經使用DI,則將上下文注入UOW並在啟動期間配置上下文。
public class UnitOfWork : IUnitOfWork {
private readonly AppDbContext _context;
public UnitOfWork(AppDbContext context) {
_context = context;
}
//...other code removed for brevity
}
並使用以下示例創建數據庫上下文。
public class AppDbContext : DbContext {
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {
}
//...other code removed for brevity
}
然后,使用依賴項注入來注冊包括上下文在內的所有內容
public void ConfigureServices(IServiceCollection services) {
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddTransient<IUnitOfWork, UnitOfWork>();
services.AddMvc();
}
配置從appsettings.json文件中讀取連接字符串。
{
"ConnectionStrings": {
"DefaultConnection": "connection string here"
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.