I want to build an app which provides web side (Blazor) and app side (Android, iOs, etc which use Web API communication). And I want to use EF Core to store my data.
The flow with Blazor and Web API is similar. So I want to use it with one package. Is there any way to Implement it?
The data tier sample, use DI
public class UserService : IUserService
{
private SqlContext db;
private IDbContextFactory<SqlContext> dbContextFactory;
public UserService(SqlContext sqlContext, IDbContextFactory<SqlContext> dbContextFactory)
{
this.db = sqlContext;
this.dbContextFactory = dbContextFactory;
}
public async Task Add(UserDTO userDTO, UserType Type)
{
var u = await db.Users.Where(u => u.Id == userDTO.Id).AsNoTracking().FirstOrDefaultAsync();
if (u is not null)
{
throw new("same ID");
}
userDTO.Type = Type;
var entity = userDTO.MapTo<UserEntity>();
entity.Type = Type;
await db.AddAsync(entity);
await db.SaveChangesAsync();
}
public async Task UpdatePassword(string userId, string password)
{
var user = await db.Users
.SingleAsync(u => u.Id == userId);
if (password != "")
{
user.Password = password.ToSHA512();
}
await db.SaveChangesAsync();
}
}
It's working fine in Web API, but not in Blazor.
Blazor sample
@inject IUserService userService
<SpaceItem><Button Icon="@IconType.Outline.Redo" OnClick="()=>ResetPwd(context.Id)">resetPass</Button></SpaceItem>
public async Task ResetPwd(string id)
{
var pwd = id.Substring(id.Length - 6);
await userService.UpdatePassword(id, pwd);
}
There is a problem, when I open the Blazor page, and use API to change password, then use Blazor reset password, the password which is in the response from the database is the last password.
https://learn.microsoft.com/en-us/aspnet/core/blazor/blazor-server-ef-core?view=aspnetcore-6.0
And I see dbcontextFactory, when I exec it, I need create every time. I need add one code in every func.
Is there any good way to get it ?