C
C#7mo 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
PixxelKick7mo 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
VeQox7mo ago
sry, with it i mean the dbcontext
Mayor McCheese
Mayor McCheese7mo ago
Why can't you inject a db context?
VeQox
VeQox7mo ago
it says the singleton IHostedService cannot consume scoped service dbcontext
Mayor McCheese
Mayor McCheese7mo ago
Inject IServiceFactory create your own scope and resolve it in the hosted service Sorry, IServiceScopeFactory
jcotton42
jcotton427mo ago
you could also use DbContextFactory
Mayor McCheese
Mayor McCheese7mo ago
using (var scope = scopeFactory.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<FooDBContext>();
}
using (var scope = scopeFactory.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<FooDBContext>();
}
PixxelKick
PixxelKick7mo 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
VeQox7mo ago
it (the service) works now thx for the help and recommendations ❤️