llevo un rato en esto, pero no puedo arreglarlo, no se como pero EF
no inicializa en un Worker Service
, he intentado de muchas maneras pero no se puede. es una API de DotNet Core 6
builder.Services.AddDbContext<IDBContext, DBContext>(options => options.UseSqlServer(connection));
// builder.Services.AddSingleton<IRegistra, Registra>();
// builder.Services.AddScoped<IRegistraFactory, RegistraFactory>();
// builder.Services.AddHostedService<Worker>();
builder.Services.AddSingleton<IHostedService, Worker>();
Worker
namespace ServiceWorker
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public readonly IDBContext _context;
// private readonly Registra _registra;
public Worker(ILogger<Worker> logger, IDBContext _context)
{
_logger = logger;
// _registra = registra;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// await _registra.Execute();
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
}
Registra
namespace ServiceWorker
{
public class Registra : IRegistra
{
// public readonly IDBContext _context;
public Registra(IDBContext context)
// public Registra()
{
// _context = context;
}
public async Task Execute()
{
Console.WriteLine("RUNNNNNNNNNNNNNNN");
await Task.Delay(5);
}
}
}
---> System.InvalidOperationException: Cannot consume scoped service 'IDBContext' from singleton 'Microsoft.Extensions.Hosting.IHostedService'.
System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: ServiceWorker.Worker': Unable to resolve service for type 'ServiceWorker.Registra' while attempting to activate 'ServiceWorker.Worker'.
---> System.InvalidOperationException: Unable to resolve service for type 'ServiceWorker.Registra' while attempting to activate 'ServiceWorker.Worker'.