So maybe there were several ways to phrase that question, but that's clear enough. I have a regular class library separate from my web project (which is built on Angular2 and Asp.Net Core) and I must persist its "core object" state throughout the web application life-cycle. My problem is that the class of such object makes accesses to the database, and I had to use DI in order to access the correct DBContext from the Angular2 application.
private Building building = null;
public AddDoorController(AutoListDbContext context) {
building = new Building(context);
}
However, I must persist building state, but from what I could gather so far, server-side classes to facilitate state persistence (such as HttpContext, TempData and so on) aren't available within the constructor's scope. I wish to keep this data server-side, surely there must be a way around it, isn't there?
EF contexts are (and should be) request-scoped. That means you can only inject them into something else with a request/transient scope. Since the context is created and destroy many times in an application's lifetime, you cannot inject it into a singleton-scoped object, which will only be created once.
If you have a singleton where you absolutely must have access to the context, you can instead inject
IServiceCollectionand use the service locator pattern, i.e.:However, you need to perform that every time you access the context. In other words, don't save that to an instance variable or field, as it will be disposed at some point. In general, the service locator pattern should be avoided, as it can lead to all sorts of issues, but sometimes you don't have a choice.
That said, though, it's very possible that you don't actually need a singleton. Things like
HttpContextare no longer statics in ASP.NET Core. If you need access toHttpContext, you simply need to injectIHttpContextAccessor. As the name implies, that lets you access the currentHttpContextinstance.Also, state that needs to be persisted between requests should be persisted, i.e. actually saved to some sort of persistent store like SQL Server or Redis. In that regard, you can setup a distributed cache and then use that to persist your object state, since distributed cache (when configured) will use SQL Server or Redis as a backing. That also lets you avoid having to singleton-scope as you can always just retrieve the object from the distributed cache whenever you need it.