Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

297
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda