使用ApplicaitonDBContext的后台线程

时间:2018-11-23 21:44:11

标签: asp.net-mvc multithreading asp.net-core-2.0

我正在尝试连接一个后台线程,该线程将每小时从Active Directory更新一次数据库。我不确定如何通过当前

UserStore

UpdateUsers()方法应该能够调用applicationDBContext.SaveChanges()方法。

如何确保LDAP管理器类可以使用Application DB上下文?

2 个答案:

答案 0 :(得分:1)

您可能想要class LdapManager : BackgroundService, ILdapManager

BackgroundService是.NET Core 2.1,有一个可用于Core 2.0的代码示例

注入IServiceScopeFactory并覆盖Task ExecuteAsync( ),在那里运行while循环。

while(!stoppingToken.IsCancellationRequested)
{
    using (var scope = _serviceScopeFactory.CreateScope())
    {
        var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
        ...; // do your stuff
    }
    await Task.Delay(myConfig.BackgroundDelay, stoppingToken);
}

这是一个不错的read about this on MSDN,其中包括2.0的代码示例

答案 1 :(得分:1)

用于从ApplicationDbContext访问HostedService

  • DbHostedService

    public class DbHostedService : IHostedService
     {
    private readonly ILogger _logger;
    
    public DbHostedService(IServiceProvider services,
        ILogger<DbHostedService> logger)
    {
        Services = services;
        _logger = logger;
    }
    
    public IServiceProvider Services { get; }
    
    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Consume Scoped Service Hosted Service is starting.");
    
        DoWork();
    
        return Task.CompletedTask;
    }
    
    private void DoWork()
    {
        _logger.LogInformation(
            "Consume Scoped Service Hosted Service is working.");
    
        using (var scope = Services.CreateScope())
        {
            var context =
                scope.ServiceProvider
                    .GetRequiredService<ApplicationDbContext>();
    
            var user = context.Users.LastOrDefault();
    
            _logger.LogInformation(user?.UserName);
        }
    }
    
    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Consume Scoped Service Hosted Service is stopping.");
    
        return Task.CompletedTask;
    }
    }
    
  • 注册DbHostedService

    services.AddHostedService<DbHostedService>();