![](/img/trans.png)
[英]Async Await on MVC Controller with repository that selects and returns a collection
[英]MVC Async Repository Pattern Doesnt Go Back to the Controller
我是MVC的新手,我正嘗試使用存儲庫服務模式創建應用程序,我盡力按照一些教程進行操作,但現在我不知道實現中有什么問題或有什么問題,因為我覺得那里確實存在問題建立時沒有任何錯誤。
我的控制器
public async Task<JsonResult> Create(string LocationName)
{
Location location = new Location
{
LocationName = LocationName
};
await _LocationService.InsertAsync(location);
var result = await _LocationService.GetAllAsync();
return Json(result, JsonRequestBehavior.AllowGet);
}
該控制器從ajax帖子接收字符串,該字符串已正確傳遞到實體Location {LocationName = LocationName}。 創建位置新對象后,將其向下傳遞到LocationService:
定位服務
public class LocationService : ILocationService
{
private ILocationRepository _LocationRepository;
public LocationService(ILocationRepository locationRepository)
{
_LocationRepository = locationRepository;
}
public async Task InsertAsync(Location entity)
{
await _LocationRepository.InsertAsync(entity);
}
//other async operations below
}
因此,對象Location到達我的LocationService,然后再次向下傳遞到LocationRepository:
位置資料庫
public class LocationRepository : ILocationRepository
{
private DefaultConnection dbContext;
private DbSet<Location> DbSet;
public LocationRepository()
{
dbContext = new DefaultConnection();
DbSet = dbContext.Set<Location>();
}
public async Task InsertAsync(Location entity)
{
DbSet.Add(entity);
await dbContext.SaveChangesAsync();
}
#region IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (dbContext != null)
{
dbContext.Dispose();
}
}
}
#endregion
}
插入了對象Location,但是在SaveAsync之后,它沒有返回我的控制器來執行其余操作。
注意:Location對象保存在數據庫中,但是我需要它返回我的控制器以返回所有Locations的JsonResult。
問題
任何幫助都感激不盡。
謝謝!
您是否嘗試過在dbContext.SaveChangesAsync()
和_LocationRepository.InsertAsync(entity)
上調用ConfigureAwait(false)
_LocationRepository.InsertAsync(entity)
?
這種死鎖很可能是由於庫中的異步方法無法在ASP.NET上下文上運行而引起的。 ConfigureAway(false)
應該使每個調用都在其自己的上下文中運行。
在Stephen的博客上有一個關於異步上下文的很好的解釋。 請查看以了解更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.