簡體   English   中英

MVC異步存儲庫模式不會返回到控制器

[英]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。

問題

  1. 為什么在SaveAsync之后不能回到我的控制器。
  2. 有什么可以改進的地方/我的實現有什么問題,以便可以做得更好。

任何幫助都感激不盡。

謝謝!

您是否嘗試過在dbContext.SaveChangesAsync()_LocationRepository.InsertAsync(entity)上調用ConfigureAwait(false) _LocationRepository.InsertAsync(entity)

這種死鎖很可能是由於庫中的異步方法無法在ASP.NET上下文上運行而引起的。 ConfigureAway(false)應該使每個調用都在其自己的上下文中運行。

在Stephen的博客上有一個關於異步上下文的很好的解釋。 請查看以了解更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM