I been searching around now for a clear cut answer on this issue, including github and still cannot see what I am missing here:
Cannot resolve scoped service 'Microsoft.EntityFrameworkCore.DbContextOptions`1[PureGateway.Data.GatewayContext]' from root provider.
In Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
//other code omitted for brevity
var connection = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<GatewayContext>(options => options.UseSqlServer(connection));
services.AddDbContextPool<GatewayContext>(options => options.UseSqlServer(connection));
services.AddScoped<IGatewayRepository, GatewayRepository>();
}
Usage:
public sealed class MatchBrokerRouteMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<MatchBrokerRouteMiddleware> _logger;
public MatchBrokerRouteMiddleware(
RequestDelegate next,
ILoggerFactory loggerFactory)
{
_next = next;
_logger = loggerFactory.CreateLogger<MatchBrokerRouteMiddleware>();
}
public async Task Invoke(HttpContext context, GatewayContext gatewayContext)
{
await _next(context);
}
I am using netcore 2.2.
you either need to use AddDbContext
or AddDbContextPool
, not both of them.
DbContextPool needs single public constructor. Check my Example below:
public partial class MyDbContext : DbContext
{
private readonly IUserResolverService _userResolverService;
public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
_userResolverService = this.GetService<IUserResolverService>();
}
}
I had this same error but found the issue was to do with service lifetime of the DbContextOptions object. By default it is "Scoped" (ie created for each request), whereas the factory expects it to be singleton.
As per this SO answer, the fix was to explicitly set the options lifetime:
services.AddDbContext<GatewayContext>(options => ApplyOurOptions(options, connectionString),
contextLifetime: ServiceLifetime.Scoped,
optionsLifetime: ServiceLifetime.Singleton);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With