C
C#11mo ago
Rezi

dependency injection problem. hangfire jobs.

so i have this problem. whenever i'm trying to inject dbcontext in my service layer for my hangfire job, i get error that db context is already being disposed. but if i do by using IserviceScopeFactory. it's working. (found this solution in chatgpt). but i don't rly like this. how can i configure hangfire so it doesn't dispose dbcontext prematurely? any ideas? public class JobService : IJobService { private readonly IServiceScopeFactory _serviceScopeFactory; public JobService(IServiceScopeFactory serviceScopeFactory) { _serviceScopeFactory = serviceScopeFactory; } public async void UpdateJobStatus() { using var scope = _serviceScopeFactory.CreateScope(); var jobRepository = scope.ServiceProvider.GetRequiredService<IJobRepository>(); } }
2 Replies
Joschi
Joschi11mo ago
How is your DBcontext registered? How does the code look that produced the error? Is JobService also registered in the DI? If so, what's it's lifetime?
Rezi
ReziOP11mo ago
everything is registered as scoped. making a db call makes an error, in this case this "await jobRepository.GetWaitingCampaigns();" here's registrations. services.AddDbContext<LoyaltyDbContext>((sp, opts) => { var auditableInterceptor = sp.GetService<UpdateAuditableEntitiesInterceptor>()!; opts.UseSqlServer(configuration.GetConnectionString("Loyalty")) .AddInterceptors(auditableInterceptor); }); services.AddScoped<IJobRepository, JobRepository>(); services.AddScoped<IJobService, JobService>();
Want results from more Discord servers?
Add your server