M
M
Mikhail Usotsky2020-08-02 23:12:50
ASP.NET
Mikhail Usotsky, 2020-08-02 23:12:50

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();

Created. Everything is as usual. But for some reason, when the program starts, the device for some reason turns on and off for half a second. GPIO is reset to zero. In a simple console application, the device normally turns on and only turns off when requested. I decided to check one device status to find the culprit of the problem. It turned out that any attempt to assign him ends in failure. It's like the classes are reset every time. Classes are only initialized once, when the Startup is created. But the variables located in Startup quietly store values.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Serafim Prozorov, 2020-08-04
@serafimprozorov

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.

Y
yuopi, 2020-08-03
@yuopi

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 question

Ask a Question

731 491 924 answers to any question