Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

299
Views
Inject Context Ef core to Worker Service project

i want inject my contect to project and use context in workers :

public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddDbContext<XContext>(options =>
                    {
                        options.UseSqlServer(
                            hostContext.Configuration["ConnectionStrings:Connection"],
                            serverDbContextOptionsBuilder =>
                            {
                                var minutes = (int)TimeSpan.FromMinutes(3).TotalSeconds;
                                serverDbContextOptionsBuilder.CommandTimeout(minutes);
                                serverDbContextOptionsBuilder.EnableRetryOnFailure();
                            });
                    });
                    //services.AddTransient<XContext>();
                    //services.AddTransient<XContext>();
                    services.AddScoped<XContext>();

                    //workers
                    services.AddHostedService<Worker1>();
                    services.AddHostedService<Worker2>();
                });
    }

workers :

     public class Worker1: BackgroundService
        {
            private readonly ILogger<Worker1> _logger;
    
            private readonly IConfiguration _configuration;
    
            private readonly TookoContext _uow;
    
             
    
            public Worker1(ILogger<Worker1> logger, IConfiguration configuration, XContext uow)
            {
                _logger = logger;
                _configuration = configuration;
                _uow = uow;
            }
   // ...
}

but i have this error :

Some services are not able to be constructed (Error while validating> the service descriptor ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: Worker1': Cannot consume scoped service 'XContext' from singleton

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You need to inject IServiceProvider into the hosted service instead, and then when you need an XContext:

using (var scope = _serviceProvider.CreateScope())
{
    var context = scope.GetRequiredService<XContext>();
    // ...
}

DBContext is intended to be short-lived, so don’t be tempted to create one when your service starts and keep it around for the lifetime of the service. You should instead create, use briefly, then dispose of them, as and when needed.

In the example above, the scope will handle disposing the context; you do not need to - and shouldn’t - do it yourself.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!