예제 #1
0
        public static IServiceCollection ConfigureDbContext([NotNull] this IServiceCollection services, [NotNull] IWebHostEnvironment environment, [NotNull] IConfiguration configuration)
        {
            services.EnsureNotNull();
            environment.EnsureNotNull();
            configuration.EnsureNotNull();

            var options = configuration.GetOption <DatabaseContextOptions>();

            if (options.UseInMemoryDatabase)
            {
                services.AddDbContext <ApplicationDbContext>(builder =>
                {
                    builder.EnableDetailedErrors(options.EnableDetailedErrors);
                    builder.UseInMemoryDatabase(options.InMemoryDatabaseName);
                });

                DataGenerator.Initialize(services);
            }
            else
            {
                void CreateOptionsAction(DbContextOptionsBuilder builder)
                {
                    builder.EnableDetailedErrors(options.EnableDetailedErrors);
                    builder.UseQueryTrackingBehavior(options.QueryTrackingBehavior);
                    builder.UseSqlServer
                    (
                        options.ConnectionString,
                        _ =>
                    {
                        _.EnableRetryOnFailure(options.MaxRetryCount, options.MaxRetryDelay, null);
                        _.CommandTimeout(options.CommandTimeout);
                    });
                }

                if (options.EnablePooling)
                {
                    services.AddDbContextPool <ApplicationDbContext>(CreateOptionsAction, options.PoolSize);
                }
                else
                {
                    services.AddDbContext <ApplicationDbContext>(CreateOptionsAction, options.ContextLifetime, options.OptionsLifetime);
                }
            }

            return(services);
        }