Answer the question
In order to leave comments, you need to log in
What's wrong with classes in ASP.Net Core?
I created a couple of separate classes (located in two separate projects) to control the device via the web (such a task) and declared in the Startup class (third project):
Device device = new Device();
Control control = new Control();
Answer the question
In order to leave comments, you need to log in
If you want instances of your classes to be created at application startup and remain available throughout its operation, you need to either make them static fields of some class, or use the Singleton pattern (never an antipattern when used correctly), or, as you said above, to use Dependency Injection, you can read about it, for example, here: https://docs.microsoft.com/ru-ru/aspnet/core/funda...
Why, in general, is happening what you described. The Startup class is created at the start of the application and is used only for its configuration, that is, it does not live all the time your application is running, and therefore, all objects that are its fields are destroyed by the garbage collector, unless ownership is transferred to another object that has a longer time life. You, as I understand it, simply create these objects in the method, in this case, again, if you do not transfer ownership, they will become inaccessible immediately after the method ends and will be collected by the garbage collector very quickly.
In asp.net core, classes should not be created this way, you need to use Dependency Injection.
In the Startup file , add
the ConfigureServices method :
services.AddSingleton();
services.AddSingleton();
And in the classes in which they need to be used - get them through the constructor.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question