Фоновый поток, который использует ApplicaitonDBContext - PullRequest
0 голосов
/ 24 ноября 2018

Я пытаюсь подключить фоновый поток, который будет обновлять базу данных раз в час из Active Directory.Я не уверен, как передать текущий

    public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("Connection")));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddSessionStateTempDataProvider();
            services.AddSession();
            services.AddHttpContextAccessor();

            services.AddSingleton(Configuration);
            services.AddScoped<IAppDbRepository, AppDbRepository>();
            services.AddScoped<IActiveDirectoryUtility, ActiveDirectoryUtility>();
            services.AddScoped<IActiveDirectoryManager, ActiveDirectoryManager>();

            services.AddHostedService<LdapManager>();
            services.AddScoped<ILdapManager, LdapManager>();

        }

In the LdapManager class I would like to call the UpdateUsers method every hour:

    public class LdapManager : ILdapManager, IHostedService
    {
        private IConfiguration _configuration = null;
        private Logging _logger;
        private List<string> ldapConnectorForDirectoryEntries = new List<string>();

        public LdapManager(IConfiguration configuration)
        {
            _configuration = configuration;

            UpdateUsers();
            SyncActiveDirectoryUsers();
        }


    public void SyncActiveDirectoryUsers()
        {
            try
            {
                using (var waitHandle = new AutoResetEvent(false))
                {
                    ThreadPool.RegisterWaitForSingleObject(waitHandle, (state, timeout) => { UpdateUsers(); }, null, TimeSpan.FromHours(1), false);
                }
            }
            catch
            {
                throw;
            }
        }
    }

Метод UpdateUsers () должен иметь возможность вызывать метод applicationDBContext.SaveChanges ().

Как я могу убедиться, что менеджер LDAPкласс может использовать контекст БД приложения?

Ответы [ 2 ]

0 голосов
/ 28 ноября 2018

Для доступа к 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>();
    
0 голосов
/ 24 ноября 2018

Вы, вероятно, хотите class LdapManager : BackgroundService, ILdapManager

BackgroundService - это .NET Core 2.1, есть пример кода, доступный для ядра 2.0

Внедрение IServiceScopeFactory и переопределение Task ExecuteAsync( ), выполните какое-то времяпетля там.

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

А вот хорошее , читайте об этом на MSDN , включая пример кода для 2.0

.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...