简体   繁体   English

无法访问已处置的对象:DataContext

[英]Cannot access a disposed object : DataContext

I'm using TCPClient to connect to device and get some data as a strings, then I'm trying to save data to DB and getting 我正在使用TCPClient连接到设备并以字符串形式获取一些数据,然后尝试将数据保存到DB并获取

"Cannot access a disposed object" error." “无法访问已处置的对象”错误。

Maybe problem is because I'm trying to save to DB from async callback function? 也许是因为我试图从异步回调函数保存到数据库? Please take a look, here are two functions: first one gets network stream, already connected to the device and starts reading data, second one is callback: 请看一下,这里有两个功能:第一个功能获取网络流,已经连接到设备并开始读取数据,第二个功能是回调:

private void ReadDataAsync(NetworkStream nwStream)
        {
            byte[] buffer = new byte[1024];

            messageStream mStream = new messageStream(nwStream, buffer);

            if (nwStream.CanRead)
            {
                Console.WriteLine("Starting async");
                nwStream.BeginRead(buffer, 0, buffer.Length,
                    new AsyncCallback(OnReadEndAsync), mStream);
            }

            else
            {
                Console.WriteLine("Cannot read stream");
            }
        }

        private void OnReadEndAsync(IAsyncResult result)
        {
            String message = "";

            messageStream mStream = (messageStream)result.AsyncState;
            int incDataSize = mStream.nwStream.EndRead(result);

            message = Encoding.ASCII.GetString(mStream.buffer, 0, incDataSize);
            List<Event> events = new List<Event>();
            events = ProcessMessage(message);
            if(events.Any())
                 _repo.saveEventsToDB(events);
            if (mStream.nwStream.CanRead)
            {
                mStream.nwStream.BeginRead(mStream.buffer, 0, mStream.buffer.Length,
                    new AsyncCallback(OnReadEndAsync), mStream);
            }
        }

Finally found a solution! 终于找到了解决方案!

So problem was that I used DataContext dependancy, which was injected in the controller constructor - and it was disposed after HTTP request was completed. 因此,问题在于我使用了DataContext依赖关系,该依赖关系已注入控制器构造函数中,并且在HTTP请求完成后就被废弃了。

So solution is to inject dependancy manually in the function itself, which needs access to the database: 因此解决方案是在函数本身中手动注入依赖关系,该函数需要访问数据库:

  1. Inject scope factory IServiceScopeFactory scopeFactory in the controller constructor. 将范围工厂IServiceScopeFactory scopeFactory注入控制器构造函数中。

  2. Add this to my function where I need access to DBcontext: 将此添加到需要访问DBcontext的函数中:

    using (var scope = _scopeFactory.CreateScope()) { var context = scope.ServiceProvider.GetRequiredService(); 使用(var scope = _scopeFactory.CreateScope()){var context = scope.ServiceProvider.GetRequiredService(); ... } ...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM