2
我試圖弄清楚EF-Core存在一些問題。
我使用MVC Core應用程序中的啓動代碼來初始化數據庫上下文。
這是我的DB背景:獲取數據訪問層內的Db上下文
public class AccountsDBContext : DbContext
{
public AccountsDBContext(DbContextOptions<AccountsDBContext> options)
:base(options)
{
}
// ...
}
和啓動代碼:
public void ConfigureServices(IServiceCollection services)
{
// Inject the account db
services.AddDbContext<AccountsDBContext>(options =>
options.UseMySQL(Configuration.GetConnectionString("AccountsStore")));
// ...
在所有exampes我看到DB Context是通過構造一個傳送到控制器(我假設通過依賴注入)並從那裏到其他實體\層。
[Route("api/[controller]")]
public class AccountsController : Controller
{
private AccountsDBContext _db;
public AccountsController(AccountsDBContext context)
{
this._db = context;
}
但是,我不是很喜歡db context將成爲控制器成員的想法。
我真的更喜歡在數據訪問層中獲取數據庫上下文,而不是將其傳遞到存儲庫類中。
有沒有辦法讓數據訪問層內的上下文?(據我所知,那裏沒有IServiceCollection,IApplicationBuilder,IServiceScopeFactory)
你應該注入你的DAL到控制器中,並且在你的DAL中構造函數期望EF上下文作爲依賴。 .Net Core的內置DI應該能夠輕鬆解決這兩個問題。請參閱https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection – haim770
如果您想在DAL中獲得(創建)dbcontext,只需在startup.cs中初始化DAL.DbContextFactory,並讓DbContextFactory在正確的時間創建dbcontext。請參見[http://stackoverflow.com/a/40837070/7045253](http://stackoverflow.com/a/40837070/7045253) –
@ haim770示例非常棒。謝謝。 – Yaron