C
C#13mo ago
VeQox

✅ asp.net background service with database

Im trying to make a background task which has a nats connection listening for incoming messages. When a message is received i want to add it to the database but with DI i cannot inject it. How can i work arround this?
10 Replies
PixxelKick
PixxelKick13mo ago
Youll have to be less ambigious in your wording here, for example:
with DI i cannot inject it
What is "it" in this sentence?
VeQox
VeQoxOP13mo ago
sry, with it i mean the dbcontext
Mayor McCheese
Mayor McCheese13mo ago
Why can't you inject a db context?
VeQox
VeQoxOP13mo ago
it says the singleton IHostedService cannot consume scoped service dbcontext
Mayor McCheese
Mayor McCheese13mo ago
Inject IServiceFactory create your own scope and resolve it in the hosted service Sorry, IServiceScopeFactory
jcotton42
jcotton4213mo ago
you could also use DbContextFactory
Mayor McCheese
Mayor McCheese13mo ago
using (var scope = scopeFactory.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<FooDBContext>();
}
using (var scope = scopeFactory.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<FooDBContext>();
}
PixxelKick
PixxelKick13mo ago
what do you mean by "it says" here try and be much more specific with your wording, where is that error coming from and what is the full problem
VeQox
VeQoxOP13mo ago
it (the service) works now thx for the help and recommendations ❤️
Want results from more Discord servers?
Add your server