I am trying to implement SQLite with IOC DI in a WinUI 3 app. I have created a minimal github project that demonstrates the issue.
The UI freezes & is intermittant, it can take a while to reproduce (approx 1 in 50 runs, proved on multiple PCs). This is the frustration & im hoping an obvious error in my code can be identified instead of having to run it that many times.
I expect that ive made a mistake and need help to identify the issue with the pattern that I have adopted.
App.cs
private IServiceProvider ConfigureServices()
{
var services = new ServiceCollection();
services.AddDbContext<SQLite_DbContext>(options => options
.UseSqlite($"{DbConString}")
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
.EnableDetailedErrors()
);
services.AddTransient<IPersonDb, PersonSQLiteDb>();
services.AddSingleton<Main_VM>();
var svcs = services.BuildServiceProvider();
return svcs;
}
protected async override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
{
m_window = new MainWindow();
m_window.Activate();
using (var db = new SQLite_DbContext())
{
await db.Database.EnsureCreatedAsync();
}
}
Db Context
public class SQLite_DbContext : DbContext
{
public SQLite_DbContext()
{
}
public DbSet<Person> People { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite(App.DbConString);
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
SQLite Db Person CRUD
public Task<List<Person>> GetAll()
{
using (db = new SQLite_DbContext())
{
return db.People.AsNoTracking().ToListAsync();
}
}
public async Task<Person> Insert(Person item)
{
try
{
using (db = new SQLite_DbContext())
{
await db.People.AddAsync(item);
await db.SaveChangesAsync();
return item;
}
}
catch (Exception ex)
{
return null;
}
}
Main ViewModel
public Main_VM(IPersonDb personDb)
{
_PersonDb = personDb;
}
public async Task LoadDb()
{
Debug.WriteLine($"Loading Db...");
var people = await _PersonDb.GetAll();
PeopleOC = new ObservableCollection<Person>(people);
PersonCount = $"{PeopleOC.Count} records";
}
please see github minimal project
Why does it intermittently freeze?