Share via

Microsoft.EntityFrameworkCore

Sahar Ash 0 Reputation points
2024-01-06T05:51:16.1433333+00:00

Hello, I am using Microsoft.EntityFrameworkCore And SQLServer2022, but I have a problem. I added DBContext to my service as scoped, but I get this error.
"The connection is already in a transaction and cannot participate in another transaction."

But if I add it as Transient, I have no problem, please guide me This is also my code

public abstract class BaseOperator<TOut>: IBaseOperation<TOut>
{
    protected readonly TOut? Out;
    protected IExceptionHandler ExceptionHandler;
    protected IUserInfo UserInfo;
    static SemaphoreSlim SemaphoreSlim = new SemaphoreSlim(1, 1);
    public BaseOperator()
    {
        ExceptionHandler = ServiceLocator.GetService<IExceptionHandler>();
        UserInfo = ServiceLocator.GetService<IUserInfo>();
    }
    public async Task<TOut> OperateAsync(IDbContextTransaction? DBTransaction = null, DbContext? AlinDBContext = null)
    {
        if (DBTransaction != null) return await OperateAsync(AlinDBContext, DBTransaction);
        await SemaphoreSlim.WaitAsync(2000);
         var Context = ServiceLocator.GetService<AlinDBContext>();
        using (var Transaction =await Context.Database.BeginTransactionAsync(isolationLevel: IsolationLevel.Serializable))
        {

            try
            {
                var Result = await OperateAsync(Context, Transaction);
                await Context.Database.CommitTransactionAsync();
                return Result;
            }
            catch (Exception e)
            {
                await Context.Database.RollbackTransactionAsync();
                throw new Exception(e.Message);
            }
            finally
            {
                await Transaction.DisposeAsync();
                SemaphoreSlim.Release();
            }
        }

    }
    protected abstract Task<TOut> OperateAsync(DbContext AlinDBContext, IDbContextTransaction Transaction);
}
public class ServiceLocator
{
    public static  IServiceProvider ServiceProvider;
    public static TService GetService<TService>() => ServiceProvider.GetService<TService>();
}

And In Program.cs :

        var ServiceProvider = Services.BuildServiceProvider();

        ServiceLocator.ServiceProvider = ServiceProvider;
Developer technologies | .NET | Entity Framework Core

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.