I do know the differences between Scoped, Singleton and Transient services lifetimes, but my knowledge is limited to a stateless, MVC application.
The root of the confusion starts when I add an EntityFramework context using AddScoped (per-request lifetime), and then, all I need to do to update my database is:
public void SaveUser()
{
db.SaveChanges();
}
This is very different from a MVC app, because there, the objects are completely decoupled from the context when, for exemple, they are converted to JSON and sent to the client, or from client to server (or, in other words, another request is made):
public void SaveUser(User updatedUser)
{
var existing = db.Users.Find(updatedUser.Id);
existing.Name = updatedUser.Name;
db.SaveChanges();
// I can also use something like Attach() or Update() instead.
}
This is possible in Razor Components because all of the objects (that I've bound to the UI) are still being tracked by the context, in a stateful way, through SignalR
. The EF Context seems to "never" be disposed.
In a MVC app, the EntityFramework context is recreated before every request, and disposed after (as you can expect from AddScoped
).
So, I have three questions:
- What exactly is a "request" in Razor Components aka. Server Side Blazor (from the service lifetime point of view)?
- What about clients loosing the connection and reconnecting after?
- Is there any situations where I need to verify if the object is "still" being tracked by the context, or this sort of problem never happens?