The question comes from a question asked by Bo. NET core multithreaded data is saved when DbContext is released.
Tcpservice injected Contentservice through a constructor, Contentservice's instance relies on Appdbcontext (inherited from the DbContext of EF Core). In Tcpservice, a new thread was initiated through Thread.Start to perform the Receive method in Tcpservice, and the operation to save the database through Contentservice in the Receive method, while accessing the APPDBCO An ntext instance occurs when an object has been disposed by an error.
object name: ' Appdbcontext '.--->system.objectdisposedexception:cannot access a disposed object. A Common Cause of this error is disposing a context the was resolved from dependency injection and then later trying to u Se the same context instance elsewhere in your application. This could occur if you is calling Dispose () on the context, or wrapping the context in a using statement. If you is using dependency injection, you should let the dependency injection container take care of disposing context in Stances.
To address this problem, try to inject IServiceProvider through the constructor instead, in Tcpservice.receive (the method executed in the new thread) through Iservicescope parsing
using (var scope = _serviceprovider.createscope ()) { var contentservice = scope. Serviceprovider.getrequiredservice<contentservice>(); // ...}
The results found that IServiceProvider was also disposed
System.ObjectDisposedException:Cannot access a disposed object. Object name: ' IServiceProvider '.
It can be inferred that an object that implements the IDisposable interface is not accessible through dependency injection in the newly created thread in ASP. (Except for singleton objects, but the type that implements the IDisposable interface is typically not registered as a singleton), that is, as soon as the request is complete, the implementation The Dispose method of an object of the IDisposable interface is called.
So how do we solve this problem?
1) The best solution is to register DbContext as a singleton
Services. Adddbcontext<appdbcontext> (options = {}, Servicelifetime.singleton);
It will bring a lot of side effects, not to be considered.
2) Save the data to the database implementation method based on dbcontextoptions (it is a singleton) manual new Appdbcontext, with this DbContext instance for saving operations.
Public classContentservice:repository<content>{ Private ReadOnlydbcontextoptions _options; PublicContentservice (Appdbcontext Context, dbcontextoptions options):Base(Context) {_options=options; } Public Override Asynctask<BOOL>Saveasync (Content entity) {using(varContext =NewAppdbcontext (_options)) {context. Set<Content>(). ADD (entity); return awaitContext. Savechangesasync () >0; } }}
Measurement is effective.
Using dependency injection in ASP. NET Core new Thread