I have my services configured and available via dependency injection. What I try to do is to get one at runtime (that's why I'm looking non-standard way). That means - not in a constructor, not hardcoded, I need to get a service dynamically exactly when it's needed.
Why? Entity Framework (Core).
Well, version 3.1 doesn't have any means to reset the data context. Yesterday I found out that if I try to remove entry blocked by foreign key constraint - the context breaks irreversibly. The EF tries to save invalid changes each time, despite the first try failed. Using Database.RollbackTransaction
doesn't help. Nothing does.
EF has more ugly "features", like default sandbox mode, where the context sees only its own changes, ignoring all external changes to the database. Like someone just thought "databases are primary single user, right?".
Anyway, no way of refreshing / reloading context in EF Core 3.1, failed write to database irreversibly breaks the context.
The way around this is to recreate the context when it needs to be refreshed / reset. That means I need to dispose the old context and create a new one.
I thought that configuring the data context service as Transient
would achieve just that. Well - not exactly. I tried to remove an entry I couldn't remove, it failed and the only way I could do any successful write to the database was to reload the Blazor page.
I think of a solution like this:
DataContext.Database.BeginTransaction();
try {
// some writing to the data context
DataContext.Database.CommitTransaction();
} catch {
DataContext.Database.RollbackTransaction();
DataContext.Dispose();
DataContext = GetService<MyDataContext>();
}
So I wonder how to get the service other then store IApplicationBuilder
in a static property.
What's wrong with calling the constructor? The constructor requires options (like the connection string), so I would need the configuration service anyway. There are other ugly hacks to get the configuration at runtime, but come on, there must be another, better and just more sane way of doing it.