Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

296
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda