Код: Выделить всё
program.csКод: Выделить всё
var connectionString = builder.Configuration.GetConnectionString("Main");
builder.Services.AddDbContextFactory(options => options.UseSqlServer(connectionString));
builder.Services.AddSingleton();
< /code>
MyDBContext.csКод: Выделить всё
public class MyDBContext : DbContext
{
public DbSet Users { get; set; }
public DbSet Orders { get; set; }
public MyDBContext(DbContextOptions options) : base(options)
{
_options = options;
}
}
< /code>
UsersSingletonServiceКод: Выделить всё
public class UsersSingletonService
{
internal List allUsers;
internal void SetDataUsers(List value)
=> allUsers = value;
}
< /code>
UsersScopedServiceКод: Выделить всё
public class UsersScopedService
{
private UsersSingletonService _usersSingletonService;
//define the DBContextFactory here?
//private IDbContextFactory _dbFactory;
public UsersScopedService(UsersSingletonService usersSingletonService)
{
//somehow get the DBContextFactory here?
//
_usersSingletonService = usersSingletonService;
}
public async ValueTask 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;
}
}
< /code>
The idea is to use a singleton to store a "cached" list of UsersМожет ли кто -нибудь дать какие -либо предложения?
Подробнее здесь: https://stackoverflow.com/questions/796 ... -in-blazor
Мобильная версия