I'm still trying to wrap my head around how to get a DbContextFactory work with a normal .cs class/singleton.
Here's what I have so far:
program.cs:
var connectionString = builder.Configuration.GetConnectionString("Main");
builder.Services.AddDbContextFactory<MyDBContext>(options => options.UseSqlServer(connectionString));
builder.Services.AddSingleton<MySingletonService>();
MyDBContext.cs:
public class MyDBContext : DbContext
{
public DbSet<Models.Users> Users { get; set; }
public DbSet<Models.Orders> Orders { get; set; }
public MyDBContext(DbContextOptions<MyDBContext> options) : base(options)
{
_options = options;
}
}
UsersSingletonService:
public class UsersSingletonService
{
internal List<Users?> allUsers;
internal void SetDataUsers(List<Users> value)
=> allUsers = value;
}
UsersScopedService:
public class UsersScopedService
{
private UsersSingletonService _usersSingletonService;
//define the DBContextFactory here?
//private IDbContextFactory<MyDBContext> _dbFactory;
public UsersScopedService(UsersSingletonService usersSingletonService)
{
//somehow get the DBContextFactory here?
//
_usersSingletonService = usersSingletonService;
}
public async ValueTask<List<Users>?> GetUsersDataAsync()
{
if (_usersSingletonService.allUsers is null)
{
//how do we get DB context here?
var myDBContext = _dbFactory.CreateDbContext();
var allUsers = await myDBContext.Users.ToListAsync();
_usersSingletonService.SetDataUsers(allUsers);
}
return _usersSingletonService.allUsers;
}
}
The idea is to use a singleton to store a "cached" list of Users which I can retrieve with a service class. I know how to inject DbContext into a .razor page but how would I use it with UsersScopedService here?
An additional issue I'm facing is the connection string is in appsettings.json so I don't know how I'd even pass it to DbContext. This code is based on someone suggesting using a DbContextFactory, but I have no idea how to use it.
Can anyone provide any suggestions?
Blazor doesn't offer usable scopes for DI so you will need a using somewhere, the best approach is to have a DbContext-per-method. That only requires a small modification:
//how do we get DB context here?
//var myDBContext = _dbFactory.CreateDbContext();
using var myDBContext = _dbFactory.CreateDbContext();
and then add UsersScopedService as a service and use constructor injection for the dbFactory.
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