Обратный вызов MemoryCache выполняется в новом потоке, а классы «внедряются зависимости» как переходные процессы, DBCont ⇐ C#
Обратный вызов MemoryCache выполняется в новом потоке, а классы «внедряются зависимости» как переходные процессы, DBCont
In our Startup.cs’s ConfigureServices method we have the following service registrations:
servicesCollection.AddMemoryCache(); servicesCollection.AddDbContext(ServiceLifetime.Transient); servicesCollection.AddTransient(); servicesCollection.AddTransient(); servicesCollection.AddScoped(); servicesCollection.AddScoped(); In the FaxService class, we have the AddToCache method that adds data to the MemoryCache and a ProcessMessagesCallBack which is the callback method that is registered as the PostEviction Callback in our MemoryCache:
private void AddToCache( IList messagesIdsCollection ) { this._logger.LogInformation( "AddToCache " ); var expirationToken = new CancellationChangeToken( new CancellationTokenSource(TimeSpan.FromMilliseconds(Int32.Parse(this._apiConfigSettings.MemoryCacheWait)+ 10)).Token ); var entry = new MemoryCacheEntryOptions(); entry.SetAbsoluteExpiration( TimeSpan.FromMilliseconds( Int32.Parse( this._apiConfigSettings.MemoryCacheWait ) ) ); entry.AddExpirationToken( expirationToken ); entry.RegisterPostEvictionCallback( ProcessMessagesCallBack ); this._memoryCache.Set( "messageIdsCollection", messagesIdsCollection, entry ); } protected void ProcessMessagesCallBack( object key, object value, EvictionReason reason, object state ) { // Invoke other new class from here: IList messagesIdsBatch = (IList)value; string hostName = Dns.GetHostName(); IList estrangedMessages = null; this._logger.LogInformation( "Processing messageIds List.... : " + String.Join( ",", messagesIdsBatch ) ); estrangedMessages = this._faxActivityProcessor.ProcessMessages( messagesIdsBatch ); } Ultimately, the ProcessMessagesCallBack callback method will invoke FaxActivityProcessor.cs class’s ProcessMessages method:
public IList ProcessMessages( IList messagesIdsColl ) { HashSet noDupesMessagesIdsHashSet = new HashSet(messagesIdsColl); IList noDupesMessagesIds = new IList(noDupesMessagesIdsHashSet.ToList()); IList reunifyingChildEmailEventsCollection = new List(); IList estrangedMessagesIds = null; try { IDictionary messagesIdsEmailRecordsIdsDictionary = this._dataAccessLayer.GetMessagesIdsEmailRecordsIdsDictionary(noDupesMessagesIds); estrangedMessagesIds = this._dataAccessLayer.ReconcileMisplaced( messagesIdsEmailRecordsIdsDictionary, messagesIdsBatch ); } catch( Exception ex ) { this._logger.Log( ex.StackTrace ); } return estrangedMessagesIds; } Correct me if I’m wrong, but the MemoryCache’s configured callback method runs on its own thread that is different from the Main thread of the application. Therefore, DataAccessLayer’s DatabaseContext (i.e Entity Framework’s DbContext ) gets disposed because it’s No longer in the Main thread.
So, when I run the aforementioned code, the ProcessMessages method throws an error when this._dataAccessLayer.ReconcileMisplaced method is invoked by throwing:
{"Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.\r\nObject name: 'DatabaseContext'."}
However, in our Startup.cs’s ConfigureServices, most of the classes were “dependency injected” as Transients so I was expecting that the callback method’s new Thread would get a new DatabaseContext instance. But, it’s strange that the application tries to access a disposed context instance.
What changes/additions do I have to make to this code that will ensure that the “Cannot access a disposed context instance” error stops?
I'm aware of Why is DBContext is disposed after putting it in IMemoryCache (.NET Core / EF Core) and Cannot access a disposed object with MemoryCache but they didn't help me with this issue.
Источник: https://stackoverflow.com/questions/727 ... njected-as
In our Startup.cs’s ConfigureServices method we have the following service registrations:
servicesCollection.AddMemoryCache(); servicesCollection.AddDbContext(ServiceLifetime.Transient); servicesCollection.AddTransient(); servicesCollection.AddTransient(); servicesCollection.AddScoped(); servicesCollection.AddScoped(); In the FaxService class, we have the AddToCache method that adds data to the MemoryCache and a ProcessMessagesCallBack which is the callback method that is registered as the PostEviction Callback in our MemoryCache:
private void AddToCache( IList messagesIdsCollection ) { this._logger.LogInformation( "AddToCache " ); var expirationToken = new CancellationChangeToken( new CancellationTokenSource(TimeSpan.FromMilliseconds(Int32.Parse(this._apiConfigSettings.MemoryCacheWait)+ 10)).Token ); var entry = new MemoryCacheEntryOptions(); entry.SetAbsoluteExpiration( TimeSpan.FromMilliseconds( Int32.Parse( this._apiConfigSettings.MemoryCacheWait ) ) ); entry.AddExpirationToken( expirationToken ); entry.RegisterPostEvictionCallback( ProcessMessagesCallBack ); this._memoryCache.Set( "messageIdsCollection", messagesIdsCollection, entry ); } protected void ProcessMessagesCallBack( object key, object value, EvictionReason reason, object state ) { // Invoke other new class from here: IList messagesIdsBatch = (IList)value; string hostName = Dns.GetHostName(); IList estrangedMessages = null; this._logger.LogInformation( "Processing messageIds List.... : " + String.Join( ",", messagesIdsBatch ) ); estrangedMessages = this._faxActivityProcessor.ProcessMessages( messagesIdsBatch ); } Ultimately, the ProcessMessagesCallBack callback method will invoke FaxActivityProcessor.cs class’s ProcessMessages method:
public IList ProcessMessages( IList messagesIdsColl ) { HashSet noDupesMessagesIdsHashSet = new HashSet(messagesIdsColl); IList noDupesMessagesIds = new IList(noDupesMessagesIdsHashSet.ToList()); IList reunifyingChildEmailEventsCollection = new List(); IList estrangedMessagesIds = null; try { IDictionary messagesIdsEmailRecordsIdsDictionary = this._dataAccessLayer.GetMessagesIdsEmailRecordsIdsDictionary(noDupesMessagesIds); estrangedMessagesIds = this._dataAccessLayer.ReconcileMisplaced( messagesIdsEmailRecordsIdsDictionary, messagesIdsBatch ); } catch( Exception ex ) { this._logger.Log( ex.StackTrace ); } return estrangedMessagesIds; } Correct me if I’m wrong, but the MemoryCache’s configured callback method runs on its own thread that is different from the Main thread of the application. Therefore, DataAccessLayer’s DatabaseContext (i.e Entity Framework’s DbContext ) gets disposed because it’s No longer in the Main thread.
So, when I run the aforementioned code, the ProcessMessages method throws an error when this._dataAccessLayer.ReconcileMisplaced method is invoked by throwing:
{"Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.\r\nObject name: 'DatabaseContext'."}
However, in our Startup.cs’s ConfigureServices, most of the classes were “dependency injected” as Transients so I was expecting that the callback method’s new Thread would get a new DatabaseContext instance. But, it’s strange that the application tries to access a disposed context instance.
What changes/additions do I have to make to this code that will ensure that the “Cannot access a disposed context instance” error stops?
I'm aware of Why is DBContext is disposed after putting it in IMemoryCache (.NET Core / EF Core) and Cannot access a disposed object with MemoryCache but they didn't help me with this issue.
Источник: https://stackoverflow.com/questions/727 ... njected-as
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Почему подключение очереди PHP-FPM, когда Max Active процессы меньше, чем общие процессы
Anonymous » » в форуме Php - 0 Ответы
- 32 Просмотры
-
Последнее сообщение Anonymous
-