Hi @jurin otruba ,
You could refer the following sample to create a BackgroundService, then in the BackgroundService, you can access the ApplicationDbContext and UserManager via the IServiceProvider. Code like this:
using Core5WebApplication.Data; //ApplicationDbContext
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Core5WebApplication.Services
{
public class TimedHostedService : IHostedService, IDisposable
{
private int executionCount = 0;
private readonly ILogger<TimedHostedService> _logger;
private Timer _timer = null!;
private readonly IServiceProvider _serviceProvider;
public TimedHostedService(ILogger<TimedHostedService> logger, IServiceProvider serviceProvider)
{
_logger = logger;
_serviceProvider = serviceProvider;
}
public Task StartAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service running.");
_timer = new Timer(DoWork, null, TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(10));
return Task.CompletedTask;
}
private void DoWork(object? state)
{
var count = Interlocked.Increment(ref executionCount);
//using ApplicationDbContext.
using (IServiceScope scope = _serviceProvider.CreateScope())
{
ApplicationDbContext _context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
_logger.LogInformation("First User Name (DBContext): {name}", _context.Users.OrderBy(c=>c.Id).FirstOrDefaultAsync().Result.UserName);
}
//using UserManger
using (IServiceScope scope = _serviceProvider.CreateScope())
{
UserManager<IdentityUser> _usermanager = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();
_logger.LogInformation("First User Name (UserManger): {name}", _usermanager.FindByEmailAsync("aa@hotmail.com").Result?.UserName);
}
_logger.LogInformation(
"Timed Hosted Service is working. {currentdate} Count: {Count}", DateTime.Now.ToString() ,count);
}
public Task StopAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
}
Then, register the host service in the Startup.cs file:
services.AddHostedService<TimedHostedService>();
After running the application, the result is like this:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion