Exemple #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper(typeof(Startup));

            services.AddMediatR(typeof(Startup));

            services.AddDbContext <DatabaseContext>(options => options.UseSqlServer(Configuration.GetConnectionString(ConnectionStringKeys.App)));

            services.AddHangfire(x => x.UseSqlServerStorage(Configuration.GetConnectionString(ConnectionStringKeys.Hangfire)));

            services.AddCorrelationId();

            services.AddOptions();

            var metricsConfigSection = Configuration.GetSection(nameof(MetricsOptions));
            var influxOptions        = new MetricsReportingInfluxDbOptions();

            Configuration.GetSection(nameof(MetricsReportingInfluxDbOptions)).Bind(influxOptions);

            var metrics = AppMetrics.CreateDefaultBuilder()
                          .Configuration.Configure(metricsConfigSection.AsEnumerable())
                          .Report.ToInfluxDb(influxOptions)
                          .Build();

            services.AddMetrics(metrics);
            services.AddMetricsReportScheduler();

            // Pipeline
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(MetricsProcessor <,>));
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(ValidationBehavior <,>));
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(RequestPreProcessorBehavior <,>));
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(RequestPostProcessorBehavior <,>));

            services.AddMvc(opt => { opt.Filters.Add(typeof(ExceptionFilter)); })
            .AddMetrics()
            .AddControllersAsServices()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddFluentValidation(cfg => { cfg.RegisterValidatorsFromAssemblyContaining <Startup>(); });

            // Identity
            var identityOptions = new Infrastructure.Identity.IdentityOptions();

            Configuration.GetSection(nameof(Infrastructure.Identity.IdentityOptions)).Bind(identityOptions);

            services.AddIdentity <User, Role>(options =>
            {
                options.Password.RequireDigit           = true;
                options.Password.RequireLowercase       = true;
                options.Password.RequireNonAlphanumeric = true;
                options.Password.RequireUppercase       = true;
                options.Password.RequiredLength         = 6;
                options.User.RequireUniqueEmail         = true;
            })
            .AddEntityFrameworkStores <DatabaseContext>()
            .AddDefaultTokenProviders();

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = identityOptions.Authority;
                options.ApiName              = identityOptions.ApiName;
                options.ApiSecret            = identityOptions.ApiSecret;
                options.RequireHttpsMetadata = _env.IsProduction();
                options.EnableCaching        = true;
                options.CacheDuration        = TimeSpan.FromMinutes(10);
            });

            IContainer container = new Container();

            container.Configure(config =>
            {
                config.Populate(services);
            });

            metrics.ReportRunner.RunAllAsync();


            // Check for missing dependencies
            var controllers = Assembly.GetExecutingAssembly().GetTypes()
                              .Where(type => typeof(ControllerBase).IsAssignableFrom(type))
                              .ToList();

            var sp = services.BuildServiceProvider();

            foreach (var controllerType in controllers)
            {
                _logger.LogInformation($"Found {controllerType.Name}");
                try
                {
                    sp.GetService(controllerType);
                }
                catch (Exception ex)
                {
                    _logger.LogCritical(ex, $"Cannot create instance of controller {controllerType.FullName}, it is missing some services");
                }
            }

            return(container.GetInstance <IServiceProvider>());
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // GraphQL
            services.AddSingleton <IDependencyResolver>(s => new FuncDependencyResolver(s.GetRequiredService));

            services.AddSingleton <IDocumentExecuter, DocumentExecuter>();
            services.AddSingleton <IDocumentWriter, DocumentWriter>();

            services.AddGraphQL(o =>
            {
                o.ExposeExceptions        = true;
                o.ComplexityConfiguration = new GQL.Validation.Complexity.ComplexityConfiguration {
                    MaxDepth = 15
                };
            })
            .AddGraphTypes(ServiceLifetime.Singleton);
            services.AddSingleton <ISchema, RootSchema>();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddDbContext <DatabaseContext>(options => options.UseSqlServer(Configuration.GetConnectionString(ConnectionStringKeys.App)));

            services.AddHangfire(x => x.UseSqlServerStorage(Configuration.GetConnectionString(ConnectionStringKeys.Hangfire)));

            services.AddOptions();

            var metricsConfigSection = Configuration.GetSection(nameof(MetricsOptions));
            var influxOptions        = new MetricsReportingInfluxDbOptions();

            Configuration.GetSection(nameof(MetricsReportingInfluxDbOptions)).Bind(influxOptions);

            var metrics = AppMetrics.CreateDefaultBuilder()
                          .Configuration.Configure(metricsConfigSection.AsEnumerable())
                          .Report.ToInfluxDb(influxOptions)
                          .Build();

            services.AddMetrics(metrics);
            services.AddMetricsTrackingMiddleware();
            services.AddMetricsEndpoints();
            services.AddMetricsReportingHostedService();

            // Pipeline
            services.AddMvc(opt => { opt.Filters.Add(typeof(ExceptionFilter)); })
            .AddMetrics()
            .AddControllersAsServices()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // Identity
            var identityOptions = new Infrastructure.Identity.IdentityOptions();

            Configuration.GetSection(nameof(Infrastructure.Identity.IdentityOptions)).Bind(identityOptions);

            services.AddIdentity <User, Role>(options =>
            {
                options.Password.RequireDigit           = true;
                options.Password.RequireLowercase       = true;
                options.Password.RequireNonAlphanumeric = true;
                options.Password.RequireUppercase       = true;
                options.Password.RequiredLength         = 6;
                options.User.RequireUniqueEmail         = true;
            })
            .AddEntityFrameworkStores <DatabaseContext>()
            .AddDefaultTokenProviders();

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = identityOptions.Authority;
                options.ApiName              = identityOptions.ApiName;
                options.ApiSecret            = identityOptions.ApiSecret;
                options.RequireHttpsMetadata = _env.IsProduction();
                options.EnableCaching        = true;
                options.CacheDuration        = TimeSpan.FromMinutes(10);
            });

            IContainer container = new Container();

            container.Configure(config =>
            {
                config.Populate(services);
            });

            metrics.ReportRunner.RunAllAsync();

            // Check for missing dependencies
            var controllers = Assembly.GetExecutingAssembly().GetTypes()
                              .Where(type => typeof(ControllerBase).IsAssignableFrom(type))
                              .ToList();

            var sp = services.BuildServiceProvider();

            foreach (var controllerType in controllers)
            {
                _logger.LogInformation($"Found {controllerType.Name}");
                try
                {
                    sp.GetService(controllerType);
                }
                catch (Exception ex)
                {
                    _logger.LogCritical(ex, $"Cannot create instance of controller {controllerType.FullName}, it is missing some services");
                }
            }

            services.AddLogging(builder => builder
                                .AddConfiguration(Configuration)
                                .AddConsole()
                                .AddDebug()
                                .AddEventSourceLogger()
                                .AddSentry());

            return(container.GetInstance <IServiceProvider>());
        }