出问题的代码如下:

 public class dbbookchaptersservice : ibookchaptersservice
    {
        private readonly bookscontext _bookscontext;
        public dbbookchaptersservice(bookscontext bookscontext)
        { _bookscontext = bookscontext;}
         public async task add(bookchapter bookchapter)
        {
           await _bookscontext.chapters.addasync(bookchapter);
           await _bookscontext.savechangesasync(); //此处写入数据库时会抛出异常                
         }
    }

经分析查找原因如下:

通过依赖注入的上下文执行到savechangesasync这个异步方法时,会直接dispose掉, 导致回调失败.

解决办法:

1. 使用同步方法savechanges().
此方法最简单, 也可以新构造一个异步方法将其包起来实现异步调用.

2. 不用依赖注入的上下文, 而是临时生成上下文, 具体步骤如下:
此方法并非完全不使用依赖注入, 只是舍弃依赖注入上下文,而使用依赖注入的dbcontextoptions<t>来构造临时上下文.

public class dbbookchaptersservice : ibookchaptersservice
    {
       private readonly bookscontext _bookscontext;
        // 1. 采用依赖注入获得dbcontextoptions
        private readonly dbcontextoptions<bookscontext> _options;        
        public dbbookchaptersservice(bookscontext bookscontext, dbcontextoptions<bookscontext> options)
        {
            _bookscontext = bookscontext;
            _options = options;
        }
         public async task add(bookchapter bookchapter)
        {
           // 2. 用optins生成临时上下文, 执行异步savechangesasync()
            using (var context = new bookscontext(_options))
            {
                await context.chapters.addasync(bookchapter);
                await context.savechangesasync();
            }