- Do several containers open at the same time and carelessly apply acceptable practices?
As a rule, this is perfectly acceptable, sometimes even necessary, but you must be careful with this. Having several containers at the same time is especially convenient when performing multi-threaded operations. Due to the fact that db works in general, each thread must have its own DbContext, which should not be shared with other threads. The disadvantage of using multiple DbContexts at the same time is that each of them will use a separate db connection, and sometimes a limited one, which can lead to the fact that the application sometimes cannot connect to the database. Another disadvantage is the fact that an entity generated by one DbContext cannot be used with an entity generated by another DbContext. In your example, HelperMethod returns a primitive type, so this is completely safe, but if it returns some object of the object that you would like to assign to MainMethod, for example, to some navigation property of the object created by MainMethod DbContext, then you will get an exception. To overcome this in MainMethod, you will need to use the Id of the object returned by HelperMethod to get this object again, this time using the fc context. On the other hand, there is the advantage of using several contexts: if one context has some problems, for example, he tried to save something that violated the index constant, then all subsequent tests of saving changes will lead to the same exception that the erroneous change is still not expected. If you use several DbContexts, then if someone fails, then the second will work independently - thatβs why DbContexts should not live long. Therefore, usually I would say that the best rule of use would be:
- Each thread must use a separate DbContext
- All methods executed in one thread must have the same DbContext
Of course, the above applies if the work performed is short. DbContext should not live long. The best example is web applications: each request to the server is processed by a separate thread, and response generation operations usually do not take much time. In this case, all methods that are executed to generate a single response should be shared for convenience by the same DbContext. But each request must be served by a separate DbContext.
- Was this problem solved in the form of some class (IoC?), Or at least some good design pattern?
What you need to do is that your DbContext class is a single point stream, but each stream has its own instance of this class. In my opinion, the best way to assure this is in IoC. For example, in Autofac in web applications, I register my DbContext with the following rule:
builder .RegisterType<MyDbContext>() .InstancePerHttpRequest();
Thus, autofac IoC generates one DbContext for each request and transfers the existing instance to the request service flow. You do not need to worry about disposing of your DbContext. Your IoC will do this when your flow is complete.