0

there will be multi request to one action .So I created a static class which has ConcurrentQueue to process the data.

but I can not use ef core in it.because it is static class.

and I have to save data and re-read data per request.

otherwise the data will be wrong.

liang.good
  • 213
  • 3
  • 12

1 Answers1

0

Static class is 100% out. You can't get it done. However, there's probably no need for an actual static class here. You should instead use a normal class, register it as a singleton, and then inject it where you need it. The context is a scoped service, so you still cannot directly inject it into the class, but you can inject IServiceProvider and use the service-locator pattern:

using var scope = _serviceProvider.CreateScope();
using var context = scope.ServiceProvider.GetRequiredService<MyContext>();
// do something with context

It's important to note that you can only use the context in within the scope of which it's defined. You cannot do something like a set a field or property on the class with it. You'll have to use the above code within each method that needs to use the context within the class.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • @Chirs Pratt Thank you for your answer. it helped me a lot. since I am following https://stackoverflow.com/a/44669109/13258745 can I use the code you gave me in the methods? – liang.good Apr 08 '20 at 13:59
  • How do you process the mutiple request? – liang.good Apr 08 '20 at 14:03
  • Based on that, you should *actually* be using this: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio#queued-background-tasks – Chris Pratt Apr 08 '20 at 14:14
  • As you say the static class is out. I want to know what is the latest way to deal with multi request? – liang.good Apr 08 '20 at 14:26