I am trying to create an API backed by mssql and entity framework.
Everything seems to go well until I start to hook up the frontend.
I am getting exceptions saying System.InvalidOperationException: The connection was not closed. The connection's current state is open.
or System.InvalidOperationException: Invalid operation. The connection is closed.
depending on which API finishes first.
I have the following in my startup.cs
services.AddDbContext<ApplicationContext>(opt => {
opt.UseSqlServer(new SqlConnection(Configuration["CONNECTIONSTRINGS_AZURECONNECTION"]), builder => builder.MigrationsAssembly("Application.Web"));
opt.UseOpenIddict();
});
services.AddIdentity<User, Role>()
.AddEntityFrameworkStores<ApplicationContext, Guid>()
.AddDefaultTokenProviders();
All of my repositories are scoped
services.AddScoped<INotificationRepository, NotificationRepository>();
And so is the database context
services.AddScoped<ApplicationContext, ApplicationContext>();
Both controllers are basically the same
private readonly INotificationRepository _notificationRepository;
public NotificationsController(UserManager<User> userManager, INotificationRepository notificationRepository)
:base(userManager)
{
_notificationRepository = notificationRepository;
}
[HttpGet]
public async Task<IActionResult> GetAsync()
{
var user = await GetCurrentUserAsync();
return new OkObjectResult(await _notificationRepository.FindByAsync(n => n.User == user));
}
Am I correct in thinking that the context needs to be scoped per request? And each chrome call is a separate request which would create a separate scope?
So each call would basically be:
Request
Auth filters
Controller
async function
async get current user -> return user (dont destroy context)
async repository function
return from repository
return from controller
Google is no help so I assume I am doing something incorrectly :)