Using dependency injection in ASP. NET Core new Thread

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.