using Database in IHostedService

493 Views Asked by At

Hi guys I try to use my Database in an IHostedService. Asp .net, SQLite I get the context with the IServiceScopeFactory. After that I Start a Timer and then I want to access the database every time the timer gets called around all 2 seconds.

If I start the application this exception will be thrown immediately after starting

System.InvalidOperationException: 'An attempt was made to use the model while it was being created. A DbContext instance cannot be used inside 'OnModelCreating' in any way that makes use of the model that is being created.'

Here the code where I am calling the Database. In the line : if (CurrentIndex > db.Municipalities.Count()) CurrentIndex = 1; the exception occours.

public WeatherRefreshService(IServiceScopeFactory serviceProvider)
{
    this.db = serviceProvider.CreateScope().ServiceProvider.GetRequiredService<SunfinderDbContext>();
}

public Task StartAsync(CancellationToken cancellationToken)
{
    var task = new Task(async () =>
    {
        timer = new Timer(
            RefreshWeatherData,
            null,
            TimeSpan.Zero,
            TimeSpan.FromMilliseconds(RefreshTime)
            );
    });
    task.Start();
    return task;
}

public async void RefreshWeatherData(object? state)
{
    if (CurrentIndex > db.Municipalities.Count()) CurrentIndex = 1;
    var currentMunicipality = db.Municipalities.Where(x => x.Id == CurrentIndex).First();
    ...
}
1

There are 1 best solutions below

0
Martin Costello On

You should resolve the database dependency inside your task (the processing loop), not in the constructor.

See here for more information and examples. The constructor captures the IServiceProvider into a field, which is used to create a scope and then the required service as part of the work loop.