Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 790
foad abdollahi Avatar asked Oct 27 '25 10:10

foad abdollahi


1 Answers

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.

like image 170
sellotape Avatar answered Oct 29 '25 23:10

sellotape