public static IWebHost BuildWebHost(string[] args) { var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile(path: $"appsettings.{environment}.json", optional: true, reloadOnChange: true) .Build(); var influxOptions = new MetricsReportingInfluxDbOptions(); configuration.GetSection(nameof(MetricsReportingInfluxDbOptions)).Bind(influxOptions); return(WebHost.CreateDefaultBuilder(args) .ConfigureMetricsWithDefaults(builder => { builder.Report.ToInfluxDb(influxOptions); }) .UseIISIntegration() // .UseMetrics() // Setup Metrics .UseStartup <Startup>() .ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(LogLevel.Error); }) .UseNLog() // NLog: setup NLog for Dependency injection .Build()); }
public static IWebHost BuildWebHost(string[] args) { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile(path: $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true, reloadOnChange: true) .Build(); var influxOptions = new MetricsReportingInfluxDbOptions(); configuration.GetSection(nameof(MetricsReportingInfluxDbOptions)).Bind(influxOptions); return(WebHost.CreateDefaultBuilder(args) .ConfigureKestrel((context, options) => { // Set properties and call methods on options }) .ConfigureMetricsWithDefaults( builder => { builder.Report.ToInfluxDb(influxOptions); }) .UseMetrics() .UseSentry() .UseStartup <Startup>() .Build()); }
public static IHost BuildWebHost(string[] args) { ConfigureLogging(); var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true) .Build(); var influxOptions = new MetricsReportingInfluxDbOptions(); configuration.GetSection(nameof(MetricsReportingInfluxDbOptions)).Bind(influxOptions); influxOptions.MetricsOutputFormatter = new MetricsInfluxDbLineProtocolOutputFormatter(); var metrics = AppMetrics.CreateDefaultBuilder() .Configuration.ReadFrom(configuration) .Report.ToInfluxDb(influxOptions) .Build(); return(Host.CreateDefaultBuilder(args) .ConfigureMetrics(metrics) .UseMetrics() .UseSerilog() .ConfigureWebHostDefaults( webBuilder => { webBuilder.UseStartup <Startup>(); }) .Build()); }
static void ConfigureMetrics(HostBuilderContext context, IServiceCollection services) { var metricsBuilder = AppMetrics.CreateDefaultBuilder() .Configuration.Configure( options => { options.Enabled = true; options.ReportingEnabled = true; }); // TODO: Перенести в basic-microservice. const string metricsSection = MicroserviceConstants.MetricsConfiguration.ConfigSection; if (!string.IsNullOrEmpty(context.Configuration[$"{metricsSection}:InfluxDb:BaseUri"])) { var configuration = context.Configuration.GetSection(metricsSection); var config = new MetricsReportingInfluxDbOptions(); configuration.Bind(config); void MetricsConfig(MetricsReportingInfluxDbOptions conf) { conf.FlushInterval = config.FlushInterval; conf.InfluxDb = config.InfluxDb; } metricsBuilder.Report.ToInfluxDb(MetricsConfig); } services.AddSingleton(metricsBuilder.Build()); }
/// <summary> /// Add the <see cref="InfluxDbMetricsReporter" /> allowing metrics to be reported to InfluxDB. /// </summary> /// <param name="metricReporterProviderBuilder"> /// The <see cref="IMetricsReportingBuilder" /> used to configure metrics reporters. /// </param> /// <param name="url">The base url where InfluxDB is hosted.</param> /// <param name="database">The InfluxDB where metrics should be flushed.</param> /// <param name="fieldsSetup">The metric fields to report as well as thier names.</param> /// <param name="lineProtocolOptionsSetup">The setup action to configure the <see cref="MetricsInfluxDbLineProtocolOptions"/> to use.</param> /// <returns> /// An <see cref="IMetricsBuilder" /> that can be used to further configure App Metrics. /// </returns> public static IMetricsBuilder ToInfluxDb( this IMetricsReportingBuilder metricReporterProviderBuilder, string url, string database, Action <MetricFields> fieldsSetup = null, Action <MetricsInfluxDbLineProtocolOptions> lineProtocolOptionsSetup = null) { if (metricReporterProviderBuilder == null) { throw new ArgumentNullException(nameof(metricReporterProviderBuilder)); } if (url == null) { throw new ArgumentNullException(nameof(url)); } if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) { throw new InvalidOperationException($"{nameof(url)} must be a valid absolute URI"); } var lineProtocolOptions = new MetricsInfluxDbLineProtocolOptions(); lineProtocolOptionsSetup?.Invoke(lineProtocolOptions); IMetricsOutputFormatter formatter; MetricFields fields = null; if (fieldsSetup == null) { formatter = new MetricsInfluxDbLineProtocolOutputFormatter(lineProtocolOptions); } else { fields = new MetricFields(); fieldsSetup.Invoke(fields); formatter = new MetricsInfluxDbLineProtocolOutputFormatter(lineProtocolOptions, fields); } var options = new MetricsReportingInfluxDbOptions { InfluxDb = { BaseUri = uri, Database = database }, MetricsOutputFormatter = formatter }; var httpClient = CreateClient(options.InfluxDb, options.HttpPolicy); var reporter = new InfluxDbMetricsReporter(options, httpClient); var builder = metricReporterProviderBuilder.Using(reporter); builder.OutputMetrics.AsInfluxDbLineProtocol(lineProtocolOptions, fields); return(builder); }
/// <summary> /// Adds InfluxDB reporting. /// </summary> /// <param name="metricsBuilder">IMetricBuilder to add InfluxDB reporting to.</param> /// <param name="influxDbOptions">Configuration options for InfluxDB reporting.</param> static void AddInfluxDb(this IMetricsBuilder metricsBuilder, MetricsReportingInfluxDbOptions influxDbOptions) { if (influxDbOptions.InfluxDb.BaseUri == null) { return; } metricsBuilder.Report.ToInfluxDb(influxDbOptions); }
// 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() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddFluentValidation(cfg => { cfg.RegisterValidatorsFromAssemblyContaining <Startup>(); }); IContainer container = new Container(); container.Configure(config => { config.Populate(services); }); metrics.ReportRunner.RunAllAsync(); return(container.GetInstance <IServiceProvider>()); }
public void ConfigureServices(IServiceCollection services, IConfiguration configuration, ITypeFinder typeFinder) { //TODO APM按需实现 return; var config = services.BuildServiceProvider().GetRequiredService <NetProOption>(); if (!config.APMEnabled) { return; } var connectionString = config.ConnectionStrings?.DecryptDefaultConnection; var influxOptions = new MetricsReportingInfluxDbOptions(); configuration.GetSection(nameof(MetricsReportingInfluxDbOptions)).Bind(influxOptions); //var esOptions = new MetricsReportingElasticsearchOptions(); //configuration.GetSection(nameof(MetricsReportingElasticsearchOptions)).Bind(esOptions); var metricsBuilder = AppMetrics.CreateDefaultBuilder() .Configuration.ReadFrom(configuration); if (influxOptions != null) { metricsBuilder = metricsBuilder.Report.ToInfluxDb(influxOptions); } //if (esOptions!= null) //{ // metricsBuilder = metricsBuilder.Report.ToElasticsearch(esOptions); //} var metricsRoot = metricsBuilder.Build(); services.AddMetrics(metricsRoot); services.AddMetricsReportingHostedService(); services.AddMetricsTrackingMiddleware(configuration); services.AddMetricsEndpoints(configuration); //健康检测 //var metricsHealth = AppMetricsHealth.CreateDefaultBuilder() // .Configuration.ReadFrom(configuration) //.HealthChecks.RegisterFromAssembly(services) //.HealthChecks.AddPingCheck("ping 百度", "www.baidu.com", TimeSpan.FromSeconds(5)) //.HealthChecks.AddHttpGetCheck("官网", new Uri("http://wwww.NetPro.com.cn"), TimeSpan.FromSeconds(30)) //.HealthChecks.AddProcessPhysicalMemoryCheck("占用内存是否超过1G", 1024*1024*1024) //.HealthChecks.AddSqlCheck("数据库连接检测", connectionString, TimeSpan.FromSeconds(60)) //.BuildAndAddTo(services); //services.AddHealth(metricsHealth); //services.AddHealthEndpoints(configuration); }
/// <summary> /// Add the <see cref="InfluxDbMetricsReporter" /> allowing metrics to be reported to InfluxDB. /// </summary> /// <param name="metricReporterProviderBuilder"> /// The <see cref="IMetricsReportingBuilder" /> used to configure metrics reporters. /// </param> /// <param name="options">The InfluxDB reporting options to use.</param> /// <returns> /// An <see cref="IMetricsBuilder" /> that can be used to further configure App Metrics. /// </returns> public static IMetricsBuilder ToInfluxDb( this IMetricsReportingBuilder metricReporterProviderBuilder, MetricsReportingInfluxDbOptions options) { if (metricReporterProviderBuilder == null) { throw new ArgumentNullException(nameof(metricReporterProviderBuilder)); } var httpClient = CreateClient(options.InfluxDb, options.HttpPolicy); var reporter = new InfluxDbMetricsReporter(options, httpClient); return(metricReporterProviderBuilder.Using(reporter)); }
public static IWebHost BuildWebHost(string[] args) { var uri = new Uri("http://127.0.0.1:8086"); //InfluxDb 配置 var metricsReportingInfluxDbOptions = new MetricsReportingInfluxDbOptions { InfluxDb = new InfluxDbOptions { BaseUri = uri, Database = "TestDev", UserName = "******", Password = "******", }, FlushInterval = TimeSpan.FromSeconds(5), HttpPolicy = new App.Metrics.Reporting.InfluxDB.Client.HttpPolicy { BackoffPeriod = TimeSpan.FromSeconds(30), Timeout = TimeSpan.FromSeconds(10), FailuresBeforeBackoff = 5 } }; //创建指标 var metrics = AppMetrics.CreateDefaultBuilder().Configuration.Configure(options => { options.AddEnvTag("developer"); options.AddAppTag("Demo"); }) .Report.ToInfluxDb(metricsReportingInfluxDbOptions).Build(); return(WebHost.CreateDefaultBuilder(args) .ConfigureMetricsWithDefaults( builder => { builder.Report.ToInfluxDb(metricsReportingInfluxDbOptions); }) .ConfigureHealthWithDefaults((context, builder) => { builder.HealthChecks.AddPingCheck("ping baidu", "www.baidu.com", TimeSpan.FromSeconds(3)); builder.HealthChecks.AddPingCheck("ping google", "www.google.com", TimeSpan.FromSeconds(3)); builder.Report.ToMetrics(metrics, new App.Metrics.Health.Reporting.Metrics.HealthAsMetricsOptions { Enabled = true, ReportInterval = TimeSpan.FromSeconds(3) }); }) .UseHealth() .UseMetrics() .UseStartup <Startup>() .Build()); }
private static void AddMetrics(IContainer container, string appName) { if (_metrics != null) { container.RegisterNonScopedSingleton <IMetrics>(_metrics); return; } var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("metricsettings.json") .Build(); var influxOptions = new MetricsReportingInfluxDbOptions(); configuration.GetSection(nameof(MetricsReportingInfluxDbOptions)).Bind(influxOptions); var metricsRoot = new MetricsBuilder() .Configuration.ReadFrom(configuration) .Configuration.Configure( options => { options.AddServerTag(); options.AddAppTag(appName); }) .Report.ToInfluxDb(influxOptions) .Build(); var metrics = new DotNetWorkQueue.AppMetrics.Metrics(metricsRoot); container.RegisterNonScopedSingleton <IMetrics>(metrics); var scheduler = new AppMetricsTaskScheduler( TimeSpan.FromSeconds(3), async() => { await Task.WhenAll(metricsRoot.ReportRunner.RunAllAsync()); }); scheduler.Start(); _metricScheduler = scheduler; _metrics = metrics; }
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureMetricsWithDefaults((builder) => { var reporting = new MetricsReportingInfluxDbOptions(); reporting.InfluxDb.BaseUri = new Uri("http://localhost:8086"); reporting.InfluxDb.Database = "monitoring"; reporting.InfluxDb.UserName = "******"; reporting.InfluxDb.Password = "******"; reporting.InfluxDb.CreateDataBaseIfNotExists = true; reporting.FlushInterval = TimeSpan.FromSeconds(5); reporting.MetricsOutputFormatter = new MetricsInfluxDbLineProtocolOutputFormatter(); builder.Report.ToInfluxDb(reporting); }) .UseMetrics() .UseUrls("http://localhost:8080") .UseStartup <Startup>();
private static void MetricsToInfluxDB(MetricsReportingInfluxDbOptions options) { options.InfluxDb.BaseUri = new Uri("http://47.99.65.174:8086/"); options.InfluxDb.Database = "AppMetricsData"; options.InfluxDb.UserName = "******"; options.InfluxDb.CreateDataBaseIfNotExists = true; options.InfluxDb.Password = "******"; //刷新时间 options.FlushInterval = TimeSpan.FromSeconds(20); //options.Filter = new MetricsFilter().WhereType(MetricType.Timer); //options.InfluxDb.RetensionPolicy = "rp"; options.InfluxDb.CreateDataBaseIfNotExists = true; options.HttpPolicy.BackoffPeriod = TimeSpan.FromSeconds(30); options.HttpPolicy.FailuresBeforeBackoff = 5; options.HttpPolicy.Timeout = TimeSpan.FromSeconds(10); //options.MetricsOutputFormatter = new MetricsInfluxDbLineProtocolOutputFormatter(); }
/// <summary> /// Add the <see cref="InfluxDbMetricsReporter" /> allowing metrics to be reported to InfluxDB. /// </summary> /// <param name="metricReporterProviderBuilder"> /// The <see cref="IMetricsReportingBuilder" /> used to configure metrics reporters. /// </param> /// <param name="url">The base url where InfluxDB is hosted.</param> /// <param name="database">The InfluxDB where metrics should be flushed.</param> /// <param name="flushInterval"> /// The <see cref="T:System.TimeSpan" /> interval used if intended to schedule metrics /// reporting. /// </param> /// <returns> /// An <see cref="IMetricsBuilder" /> that can be used to further configure App Metrics. /// </returns> public static IMetricsBuilder ToInfluxDb( this IMetricsReportingBuilder metricReporterProviderBuilder, string url, string database, TimeSpan flushInterval) { if (metricReporterProviderBuilder == null) { throw new ArgumentNullException(nameof(metricReporterProviderBuilder)); } if (url == null) { throw new ArgumentNullException(nameof(url)); } if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) { throw new InvalidOperationException($"{nameof(url)} must be a valid absolute URI"); } var options = new MetricsReportingInfluxDbOptions { FlushInterval = flushInterval, InfluxDb = { BaseUri = uri, Database = database } }; var httpClient = CreateClient(options.InfluxDb, options.HttpPolicy); var reporter = new InfluxDbMetricsReporter(options, httpClient); var builder = metricReporterProviderBuilder.Using(reporter); builder.OutputMetrics.AsInfluxDbLineProtocol(); return(builder); }
public static IWebHost BuildWebHost(string[] args) { ConfigureLogging(); var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true) .Build(); var influxOptions = new MetricsReportingInfluxDbOptions(); configuration.GetSection(nameof(MetricsReportingInfluxDbOptions)).Bind(influxOptions); influxOptions.MetricsOutputFormatter = new MetricsInfluxDbLineProtocolOutputFormatter(); var metrics = AppMetrics.CreateDefaultBuilder() .Configuration.ReadFrom(configuration) .Report.ToInfluxDb(influxOptions) .Build(); return(WebHost.CreateDefaultBuilder(args) .ConfigureMetrics(metrics) .ConfigureHealthWithDefaults( (context, builder) => { builder.OutputHealth.AsPlainText() .OutputHealth.AsJson() .HealthChecks.AddCheck("check 1", () => new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy())) .HealthChecks.AddCheck("check 2", () => new ValueTask <HealthCheckResult>(HealthCheckResult.Degraded())) .HealthChecks.AddCheck("check 3", () => new ValueTask <HealthCheckResult>(HealthCheckResult.Unhealthy())) .Report.ToMetrics(metrics); }) .UseHealth() .UseMetrics() .UseSerilog() .UseStartup <Startup>() .Build()); }
public static IWebHost BuildWebHost(string[] args) { ConfigureLogging(); var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true) .Build(); var influxOptions = new MetricsReportingInfluxDbOptions(); configuration.GetSection(nameof(MetricsReportingInfluxDbOptions)).Bind(influxOptions); return(WebHost.CreateDefaultBuilder(args) .ConfigureMetricsWithDefaults( builder => { builder.Report.ToInfluxDb(influxOptions); }) .UseMetrics() .UseSerilog() .UseStartup <Startup>() .Build()); }
private MetricsReportingInfluxDbOptions GetOptions(IConfigurationSection configuration) { var options = new MetricsReportingInfluxDbOptions(); options.InfluxDb.BaseUri = configuration.GetValue <Uri>("BaseUri"); options.InfluxDb.Database = configuration.GetValue <string>("Database"); options.InfluxDb.UserName = configuration.GetValue <string>("UserName"); options.InfluxDb.Password = configuration.GetValue <string>("Password"); options.InfluxDb.RetentionPolicy = configuration.GetValue <string>("RetentionPolicy"); options.InfluxDb.CreateDataBaseIfNotExists = configuration.GetValue <bool>("CreateDatabaseIfNotExists"); var retentionTime = configuration.GetValue <TimeSpan?>("RetentionPolicyTimespan"); if (retentionTime != null) { options.InfluxDb.CreateDatabaseRetentionPolicy = new RetentionPolicyOptions { Duration = retentionTime, Name = options.InfluxDb.RetentionPolicy }; } return(options); }
// 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>()); }
// 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) { services.AddAutoMapper(typeof(Startup)); services.AddMediatR(typeof(Startup)); services.AddDbContext <DatabaseContext>(options => options.UseNpgsql(Configuration.GetConnectionString(ConnectionStringKeys.App))); services.AddHangfire(x => x.UsePostgreSqlStorage(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.AddMetricsTrackingMiddleware(); services.AddMetricsEndpoints(); services.AddMetricsReportingHostedService(); // Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "Knowledge API", Description = "Knowledge API v1", TermsOfService = "None", Contact = new Contact { Name = "Mads Engel Lundt", Email = "*****@*****.**", Url = "https://elcc.dk" } }); c.CustomSchemaIds(x => x.FullName); }); // 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)); opt.Filters.Add(typeof(LocaleFilterAttribute)); }) .AddMetrics() .AddControllersAsServices() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .AddFluentValidation(cfg => { cfg.RegisterValidatorsFromAssemblyContaining <Startup>(); }); // Identity var identityOptionsSection = Configuration.GetSection(nameof(Infrastructure.Identity.IdentityOptions)); services.Configure <Infrastructure.Identity.IdentityOptions>(identityOptionsSection); // configure jwt authentication var identityOptions = identityOptionsSection.Get <Infrastructure.Identity.IdentityOptions>(); var key = Encoding.ASCII.GetBytes(identityOptions.ApiSecret); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.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); //}) .AddJwtBearer("Bearer", options => { options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }; options.Audience = identityOptions.Audience; }); IContainer container = new Container(); container.Configure(config => config.Populate(services)); var mediator = container.GetInstance <IMediator>(); GlobalConfiguration.Configuration.UseMediator(mediator); 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>()); }