I'm trying to do a periodic job on my clients
using a hosted service. This is my hosted service:
namespace Commander.Services
{
public class UpdateClientsStateService : IHostedService, IDisposable
{
private readonly ILogger<UpdateClientsStateService> logger;
private readonly IServiceScopeFactory scopeFactory;
private Timer timer;
public UpdateClientsStateService(ILogger<UpdateClientsStateService> logger, IServiceScopeFactory scopeFactory)
{
this.logger = logger;
this.scopeFactory = scopeFactory;
}
public void Dispose()
{
timer?.Dispose();
}
public Task StartAsync(CancellationToken cancellationToken)
{
timer = new Timer(o =>
{
using var scope = scopeFactory.CreateScope();
var clientRepository = scope.ServiceProvider.GetRequiredService<CommanderDbContext>();
var clients = clientRepository.Clients;
foreach (var client in clients)
{
logger.LogInformation($"{client.Id}");
}
}, null, TimeSpan.Zero, TimeSpan.FromSeconds(10));
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
}
Whenever I try to get the CommanderDbContext service, iisexpress says:
The program '[16808] iisexpress.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'.
This is my ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CommanderDbContext>(opt => opt.UseMySql(Configuration.GetConnectionString("MySql")));
services.AddControllers().AddNewtonsoftJson();
services.AddScoped<IRequestRepository, SqlServerRequestRepository>();
services.AddScoped<IClientRepository, SqlServerClientRepository>();
services.AddHttpContextAccessor();
services.AddHostedService<UpdateClientsStateService>();
services.AddSingleton(o =>
{
var accessor = o.GetRequiredService<IHttpContextAccessor>();
var request = accessor.HttpContext.Request;
var uri = string.Concat(request.Scheme, "://", request.Host.ToUriComponent());
return new PaginationUriService(uri);
});
}