jbogard / MediatR.Extensions.Microsoft.DependencyInjection

MediatR extensions for Microsoft.Extensions.DependencyInjection
MIT License
326 stars 90 forks source link

System.InvalidOperationException when using MediatR with AddDbContextPool #82

Open Icidis opened 4 years ago

Icidis commented 4 years ago

Hi,

I'm getting a "System.InvalidOperationException" exception when trying to use MediatR and EF Core, but specifically only when using DbContextPooling.

Startup

var sqlConnectionStringBuilder = new SqlConnectionStringBuilder(serviceConfig.SqlConnectionString);
services.AddDbContextPool<MyDbContext>(options =>
                                options.UseSqlServer(sqlConnectionStringBuilder.ConnectionString, options =>
                                {
                                    options.CommandTimeout(serviceConfig.CommandTimeout);
                                }));

RequestHandler

public class DataLoader
        IRequestHandler<GetData, Data>,
    {
        private readonly ILogger _logger;
        private readonly IMapper _mapper;
        private readonly MyDbContext _context;

        public DataLoader(ILogger<DataLoader> logger, IMapper mapper, MyDbContext context)
        {
            _mapper = mapper;
            _context = context;
            _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        }

        /// Omitted

    }

Here's a small snippet of the stack trace

System.InvalidOperationException:
   at MediatR.Internal.RequestHandlerBase.GetHandler (MediatR, Version=8.0.0.0, Culture=neutral, PublicKeyToken=bb9a41a5e8aaa7e2)

Inner exception

Inner exception System.InvalidOperationException handled at MediatR.Internal.RequestHandlerBase.GetHandler:
   at Microsoft.EntityFrameworkCore.Internal.DbContextPool`1..ctor (Microsoft.EntityFrameworkCore, Version=3.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60)

Let me know if you want more information or the entire stack trace?