我有一個 WPF 應用程式,其視圖模型呼叫資料訪問類來執行資料庫作業。DataAccess 類具有所有異步功能,VM 使用 await _dataAccess.DoWork(withItem); 有時我會收到一個錯誤,提示在同一背景關系中執行了兩個操作。除非服務提供者在對 GetService 的不同呼叫中使用相同的背景關系,否則這是不可能的。
在 App.xaml.cs 中
services.AddDbContext<MyItemDbContext>(options =>
{
options.UseLoggerFactory(_loggerFactory);
options.UseSqlServer(config.GetConnectionString("My_Items_ConnectionString"));
});
// register concrete class for IDataAccess
services.AddScoped<IDataAccess, ItemDataAccess>();
在查看代碼
private async void BtnReady_Click(object sender, RoutedEventArgs e)
{
await SetStatusForSelectedItem(StatusIds.Ready);
}
private async Task SetStatusForSelectedItems(StatusIds statusId)
{
// get selected itemDetail item from grid
await _mainWindowVM.UpdateItemDetailState(itemDetail, stateId);
}
在 ViewModel 代碼中
private readonly IDataAccess _dataAccess;
public MainWindowVM(IDataAccess dataAccess)
{
_dataAccess = dataAccess;
}
public async Task UpdateItemDetailState(Item item, StatusIds stateId)
{
// other necessary code
item.StateId = stateId;
await _dataAccess.UpdateItem(item);
}
在 DataAccess (DalBase) 代碼中
private readonly IServiceProvider _serviceProvider;
public DalBase(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
protected MyItemDbContext Get_Item_DbContext()
{
return _serviceProvider.GetService<MyItemDbContext>();
}
// other contexts for different purposes
在 DataAccess(派生)中
public ItemDataAccess(IServiceProvider serviceProvider) : base(serviceProvider) { }
public async Task UpdateItem(Item item)
{
MyItemDbContext db = Get_Item_DbContext(); // <<< === should be new instance each time, right?
db.Items.Update(item);
await db.SaveChangesAsync();
}
I'm following this pattern throughout except that I took out a lot of try...catch to cut the size. Each of the functions in the DataAccess starts out with a call to Get_Item_DbContext() I used to have have using (var db = Get_Item_DbContext()) but an article I read said to let dependency injection decide on the lifespan. I can't find any place where I'm not using await on an async function but I get an error like this...
A second operation was started on this context before a previous operation completed...
There's one operation that's working through the list and it calls this update status function, and there's a button that the user can use to call the same function. That's when I get the error.
EDIT I used to have using (var db = Get_Item_DbContext) but then I got a different error... Cannot access a disposed context instance.
UPDATE I tried having the context injected into DalBase. I still get the error when I click run the second operation. In this case it's probably because both operations run through the same VM which now has one _dataAccess and a single context that was injected. I was trying to avoid that by getting a new instance from each function.
So my questions are these How can I find out which threads (and their call stacks) are getting the same context? Why do two separate threads (from async calls) getting the same context from GetService? Is there an option that I have to add to the AddDbContext to make it scope correctly?
Thanks Mike
uj5u.com熱心網友回復:
我建議停止在類中注入 ServiceProvider 并像這樣獲得你的服務。我稱之為反模式(服務定位器)。而是直接在類中注入您的依賴項。
所以與其:
在 DataAccess (DalBase) 代碼中
private readonly MyItemDbContext _myItemDbContext;
public DalBase(MyItemDbContext myItemDbContext)
{
_myItemDbContext = myItemDbContext;
}
// Don't expose the myItemDbContext from this class. Just use it to what you need
// other contexts for different purposes
在 DataAccess(派生)中
private readonly MyItemDbContext _myItemDbContext;
public ItemDataAccess(MyItemDbContext myItemDbContext)
{
_myItemDbContext = myItemDbContext;
}
public async Task UpdateItem(Item item)
{
_myItemDbContext.Items.Update(item);
await _myItemDbContext.SaveChangesAsync();
}
如果您不將 MyItemDbContext 的使用公開給其他類,我認為您的問題會消失。
uj5u.com熱心網友回復:
作為 WPF 應用程式,需要對管理 EF DbContext 有一些不同的看法。許多關于依賴注入和生命周期范圍的例子都指的是 Web 應用程式,這些應用程式通常定義了明確的生命周期范圍,即 Web 請求。在這些情況下,您可以使用“每個請求”生命周期范圍直接向容器注冊您的 DbContext,一切都可以正常作業。WPF 沒有明確的范圍,因為視圖被渲染并回應事件。因此,您必須明確定義 DbContext 的生命周期范圍。通常這是通過作業單元模式完成的,您的依賴項注入器可以在其中提供 UoW 范圍工廠。
使用某種using(var context = new AppDbContext())方法本身并沒有錯,但有一個非常重要的細節必須遵守:在 DbContext 范圍內讀取的物體實體必須保留在該 DbContext 的范圍內,否則將被分離并作為-是從那時起的狀態。這意味著像延遲加載這樣可以按需獲取相關資料的功能只有在 DbContext 處于范圍內時才有效。
當你有這樣的代碼時:
using(var context = new AppDbContext())
{
var order = context.Orders.Single(x => x.OrderId == orderId);
orderForm.Model = order;
}
或類似的東西,我們定義了一個背景關系范圍,獲取一個物體,然后將該參考共享給任何東西,我們允許該物體參考離開產生它的 DbContext 的范圍。該物體現在是處于孤立狀態的分離物體。我們可以訪問它的屬性,但是當我們嘗試訪問在加載之前未被 DbContext 預先加載或填充的任何導航屬性時,我們將收到錯誤。該物體仍認為它已附加到 DbContext,但該 DbContext 已被釋放。我們可以明確地分離它:
using(var context = new AppDbContext())
{
var order = context.Orders.Single(x => x.OrderId == orderId);
context.Entity(order).State = EntityState.Detached;
orderForm.Model = order;
}
或在不跟蹤的情況下加載它:
using(var context = new AppDbContext())
{
var order = context.Orders.AsNoTracking().Single(x => x.OrderId == orderId);
orderForm.Model = order;
}
這將有效地做同樣的事情,回傳一個分離的物體。但是現在,如果您嘗試訪問未加載的導航屬性,您將遇到 #nulls。這可能是有問題的,因為 #null 是否意味著訂單實際上沒有參考,或者只是沒有預取?
您讓服務定位器按需提供 DbContext 的更改避免了“超出范圍”的問題,但現在的問題是每次呼叫Get_Item_DbContext()都將回傳該單個 DbContext 實體,并且您一定會遇到跨執行緒例外,如果您正在嘗試異步或通過作業執行緒運行操作。要使用服務定位器解決此問題,您需要顯式管理 DbContext 的范圍,并了解何時應該提供共享 DbContext 實體與新的 DbContext 實體。這仍然會導致在這些范圍之間傳遞物體的問題。(即在作業執行緒上加載并回傳到具有不同 DbContext 實體的另一個執行緒。)
應盡可能避免使用分離的物體。它們不僅會導致錯誤和潛在的無效資料狀態,而且還存在用陳舊值覆寫資料的風險。延遲加載是系統在需要時依靠它按需加載資料的便捷支柱,但是圍繞它進行設計意味著您的應用程式將因許多 SELECT n 1 性能問題而陷入困境。在設計系統時,無論是 Web 還是 WPF Windows 應用程式,我的建議是利用 POCO 視圖模型來處理所有離開 DbContext 范圍的資料,并僅在絕對必要時保持這些 DbContext 實體打開。
using(var context = new AppDbContext())
{
var orderViewModel = context.Orders
.Where(x => x.OrderId == orderId)
.Select(x => new OrderViewModel
{
// Populate view model with just the fields about the order and related data that the view needs.
}).Single();
orderForm.Model = orderViewModel;
}
或者使用 Automapper:
//Note: Configuration can be centralized elsewhere, and can include any/all mappings for the entire root aggregate (Order and it's associated entities)
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderViewModel>());
using(var context = new AppDbContext())
{
var orderViewModel = context.Orders
.Where(x => x.OrderId == orderId)
.ProjectTo<OrderViewModel>(config)
.Single();
orderForm.Model = orderViewModel;
}
While a disconnected entity can have required navigation properties eager loaded and passed to a view, projecting down to a view model can produce much more efficient queries, future-proofs the system from unintentional errors or performance issues etc. when new relationships are appended, and helps avoid confusion when passing entity references around where methods may get attached or detached entities in various levels of completion. (You can easily differentiate between the view model and the associated entity)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/352434.html
標籤:c# entity-framework mvvm dependency-injection async-await
上一篇:Shell/Bash-字串之間的相等性檢查在匹配時回傳1
下一篇:根據其他行插入缺失值
