I’m new to DI and I ran into a problem. I’m making an Avalonia App(C#) which uses a local postgreSQL database. When registering into the app, it will concurrently check if the email and username already exist in the database, and therefore showing the according error :
private async Task registerCommand()
{
var service = this.user_service;
Task<bool> exists_username = service.ExistsByUsernameAsync(this.UsernameField.Text);
Task<bool> exists_email = service.ExistsByEmailAdressAsync(this.EmailField.Text);
var results = await Task.WhenAll(exists_username , exists_email);
//////
InvalidOperationException: A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext
and
ReactiveUI.UnhandledErrorException: ‘An object implementing IHandleObservableErrors (often a ReactiveCommand or ObservableAsPropertyHelper) has errored, thereby breaking its observable pipeline. To prevent this, ensure the pipeline does not error, or Subscribe to the ThrownExceptions property of the object in question to handle the erroneous case.
Concurrently using the same instance of dbcontext? I’m registering at as a scoped service.
public static void AddCommonServices(this IServiceCollection collection)
{
collection.AddScoped<UserService>();
collection.AddScoped<IUserRepository, UserRepository>();
collection.AddScoped<DatabaseContext>();
}
User Repository:
public class UserRepository : IUserRepository
{
private DatabaseContext context = null!;
public UserRepository(DatabaseContext dbcontext) => this.context = dbcontext;
User Service :
public class UserService
{
private IUserRepository repository;
public UserService(IUserRepository userRepository) => this.repository = userRepository;
Where it all begins:
private void goToRegister() => this.authVM.AuthContent = new RegisterVM(authVM, services.GetRequiredService<UserService>());
Help please?
I should add that when doing the 2 tasks one by one, they work just fine, so my quess is that the same dbcontext is called from different threads;