Ejemplo n.º 1
0
        private static void EnsureDbCreated(
            ILogger <Program> logger,
            IPatientDbService patientDbService,
            IWebHostEnvironment webHostEnvironment)
        {
            int  retries = 0;
            bool created = false;

            if (webHostEnvironment.IsDevelopment())
            {
                logger.LogInformation("Creating new database.");

                do
                {
                    try {
                        patientDbService.EnsureDeleted();
                        patientDbService.EnsureCreated();

                        created = true;
                    } catch (Exception e) {
                        if (retries < MaxRetries)
                        {
                            logger.LogError(e, "Connection to DBMS failed. Retrying connection.");
                            System.Threading.Thread.Sleep(5000);

                            retries++;
                        }
                        else
                        {
                            logger.LogCritical(e, "Failed to connect to create database.");
                            throw;
                        }
                    }
                } while (!created);
            }
            else
            {
                if (!patientDbService.CanConnect())
                {
                    logger.LogInformation("Cannot connect to database, Creating new database.");

                    do
                    {
                        try {
                            patientDbService.EnsureCreated();
                        } catch (Exception e) {
                            if (retries < MaxRetries)
                            {
                                logger.LogError(e, "Connection to DBMS failed. Retrying connection.");
                                System.Threading.Thread.Sleep(5000);

                                retries++;
                            }
                            else
                            {
                                logger.LogCritical(e, "Failed to connect to create database.");
                                throw;
                            }
                        }
                    } while (!created);
                }
            }
        }