How to avoid multi-threading issue with DbContext in ABP?

162 Views Asked by At

I am using aspnet boiler plate with .net core 3.1 project. I've a use case where I need to create separate threads for each service bus topic and then all threads will call a repo to get some data from database.

IRepository<Product, long> _productRepository

Now I want to ask should I avoid using IRepository because of multi-threading issue with DbContext or will IRepository will manage it? If not, how can I resolve it? I assume by creating a lifetime scope for DbContext. But does ABP boilerplate provides something to handle this? E.g "IUnitOfWorkManager"

Also if creating a lifetime scope for DbContext is the only option, can someone share a snippet to do that with ABP. Thanks

Update: I am creating a lifetime scope right at the beginning as well:

 var topics = await _queueAdmin.GetAllTopicsAsync();
 var tasks = topics.Select(async topic =>
 {
     using (var scope = _serviceProvider.CreateScope())
     {
         var queue = scope.ServiceProvider.GetRequiredService<IQueue>();

         await queue.ProcessTopicMessagesAsync<T>(topic, subscriptionName, callback, cancellationToken);
     }
 });

 await Task.WhenAll(tasks);

Update 2: I've a topic per tenant in service bus. I've a background service that runs every 15 mins and process all messages from all topics in parallel. I am extracting a chunk of 50 messages from a topic and send a db call to get some info about each message and then send it to a microservice that dumps it in a DB and it keeps on doing it until the topic is clear. IQueue is registered as scoped

IocManager.IocContainer.Register(
    Component
        .For<IQueue>()
        .ImplementedBy<ServiceBusQueueService>()
        .LifestyleCustom<MsScopedLifestyleManager>()
);
0

There are 0 best solutions below