// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureContainer(ServiceRegistry services) { services.AddControllers(); var config = Configuration.GetSection("Explorer").Get <ExplorerConfig>(); services.AddSingleton(config); services.AddAircloakJsonApiServices <ExplorerApiAuthProvider>(); // Singleton services services .AddSingleton <ExplorationRegistry>() .AddSingleton <ExplorationLauncher>(); // Scoped services services .AddScoped <MetricsPublisher, SimpleMetricsPublisher>() .AddScoped <ContextBuilder>() .AddScoped <AircloakConnectionBuilder>(); // Register Explorer Components services.IncludeRegistry <ComponentRegistry>(); if (Environment.IsDevelopment()) { services.AddCors(options => options.AddDefaultPolicy(b => b.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin())); } }
public void ConfigureContainer(ServiceRegistry services) { services.AddCors(options => { options.AddPolicy("AllowExpensesMgr", builder => builder.WithOrigins("http://localhost:49602")); }); services.AddJwtConfiguration(Configuration); services.AddSwaggerConfiguration(); services.AddApplication(); services.AddInfrastructure(Configuration); services.AddControllers(); // Also exposes Lamar specific registrations // and functionality services.Scan(s => { s.AssembliesAndExecutablesFromApplicationBaseDirectory(a => a.FullName.Contains("Application")); s.AssembliesAndExecutablesFromApplicationBaseDirectory(a => a.FullName.Contains("Infrastructure")); s.TheCallingAssembly(); s.WithDefaultConventions(); s.SingleImplementationsOfInterface(); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureContainer(ServiceRegistry services) { services.AddCorrelationId(); services.AddHttpContextAccessor(); services.AddMvc(); services.AddVersionedApiExplorer(options => options.GroupNameFormat = "'v'VVV"); services.AddApiVersioning(o => { o.ReportApiVersions = true; o.DefaultApiVersion = new ApiVersion(1, 0); o.AssumeDefaultVersionWhenUnspecified = true; }); services.AddOptions(); services.AddMemoryCache(); services.AddHttpClient(); services.AddSwagger(Configuration); services.AddDependencyInjection(Configuration); services.AddControllers(); services.AddHealthChecks(); services.AddApiAuthentication(Configuration); services.AddSwaggerGen(c => { // This coupled with the properties in the csproj allow the swagger page to show additional comments for methods var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); services.AddCors(); }
public void ConfigureContainer(ServiceRegistry services) { services.AddOptions(); services.Configure <KafkaOptions>(Configuration.GetSection("Kafka")); services.AddControllers(); services.AddMvc() .AddJsonOptions(options => { options.JsonSerializerOptions.IgnoreNullValues = true; }); services.AddLogging(); services.AddRouting(option => { option.LowercaseUrls = true; }); services.For <IMediator>().Use <Mediator>().Transient(); services.For <ServiceFactory>().Use(ctx => ctx.GetInstance); services.AddCors(options => { options.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }); }); //Kafka services.For(typeof(IKafkaPublisher <>)).Add(typeof(KafkaPublisher <>)).Scoped(); services.AddHostedService <BaselineListener>(); services.AddTransient <IUserInput, UserInput>(); services.AddTransient <ITradeAlgorithm, TradeAgorithm>(); services.AddMemoryCache(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureContainer(ServiceRegistry services) { services.AddControllers(); InfrastructureRegister.Register(services, Configuration); services.IncludeRegistry <ServiceRegister>(); services.Scan(s => { s.TheCallingAssembly(); s.WithDefaultConventions(); }); services.AddCors(); }
private static void InitializeCors(ServiceRegistry services) { services.AddCors( options => { options.AddPolicy( "All", builder => builder .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials()); }); }
public void ConfigureContainer(ServiceRegistry services) { // Supports ASP.Net Core DI abstractions services.AddOptions(); services.Configure <KafkaOptions>(Configuration.GetSection("Kafka")); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Order APIs", Version = "v1" }); }); services.AddEntityFrameworkSqlServer() .AddDbContext <OrdersDBContext>(options => { options.UseSqlServer(Configuration["ConnectionString"], sqlServerOptionsAction: sqlOptions => { sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name); sqlOptions.EnableRetryOnFailure(maxRetryCount: 3, maxRetryDelay: TimeSpan.FromSeconds(1), errorNumbersToAdd: null); }); }); services.AddMvc() .AddJsonOptions(options => { options.JsonSerializerOptions.IgnoreNullValues = true; }); services.AddLogging(); services.AddControllers(); services.Scan(scanner => { scanner.AssemblyContainingType <CreateOrderCommand>(); scanner.AssemblyContainingType <CreateItemCommand>(); scanner.AssemblyContainingType <CreateItemsCommand>(); scanner.AssemblyContainingType <RollbackOrderCommand>(); scanner.AssemblyContainingType <GetItemQuery>(); scanner.AssemblyContainingType <GetItemsQuery>(); scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler <,>)); }); services.For <IMediator>().Use <Mediator>().Transient(); services.For <ServiceFactory>().Use(ctx => ctx.GetInstance); services.For(typeof(IItemRepository)).Add(typeof(ItemRepository)).Singleton(); services.For(typeof(IOrderRepository)).Add(typeof(OrderRepository)).Singleton(); services.For(typeof(IKafkaProducer <>)).Add(typeof(KafkaProducer <>)).Singleton(); services.For(typeof(IKafkaSubscriber <>)).Add(typeof(KafkaSubscriber <>)).Singleton(); services.For(typeof(IKafkaMessageService <,>)).Add(typeof(KafkaMessageService <,>)).Singleton(); services.AddCors(options => { options.AddDefaultPolicy(builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }); }); // services.AddHostedService<PaymentBackgroundAvroService>(); // services.AddHostedService<PaymentBackgroundJsonService>(); }
public void ConfigureContainer(ServiceRegistry services) { services.AddControllers(); services.Configure <AppSettings>(Configuration.GetSection("AppSettings")); services.AddCors(); services.AddLogging(); services.Scan(s => { s.TheCallingAssembly(); s.WithDefaultConventions(); s.AssemblyContainingType <CommonRegistry>(); s.AssemblyContainingType <ServicesRegistry>(); s.AssemblyContainingType <DefaultRegistry>(); }); }
public void ConfigureContainer(ServiceRegistry services) { // Add Dave services.AddDave(Configuration); // Add Dave Logging (serilog) services.AddDaveLoggerSerilog(builder => { if (HostingEnvironment.IsDevelopment()) { builder.DiagnoticDebug = Configuration.GetValue <bool>("AddDiagnosticDebug", false); } }); services.Add__DT_PROJECT_NAME(); services.AddCors(); services.AddMvc(m => { // uncomment to use YodaServiceResult //m.AddYodaService(); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // Add Swagger integration services.AddSwaggerGen(options => { options.OperationFileResultFilter(); options.MapType <Stream>(() => new Schema { Type = "file" }); options.SwaggerDoc("v1", new Info { Title = "__DT_PROJECT_NAME", Version = "v1", Description = "__DT_PROJECT_NAME Web Api" }); options.CustomOperationIds(ad => $"{ad.ActionDescriptor.RouteValues["controller"]}_{ad.ActionDescriptor.RouteValues["action"]}"); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); options.IncludeXmlComments(xmlPath); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureContainer(ServiceRegistry services) { services.AddControllers().AddJsonOptions(options => options.JsonSerializerOptions.Converters.Add(new ExploreMetricConverter())); services.AddApiVersioning(); const string ConfigSection = "Explorer"; services.Configure <ExplorerOptions>(Configuration.GetSection(ConfigSection)); services.Configure <ConnectionOptions>(Configuration.GetSection(ConfigSection)); services.AddAircloakJsonApiServices <ExplorerApiAuthProvider>(); // Enriched event logger for sentry services.AddScoped <ISentryEventProcessor, ExplorerEventProcessor>(); // Singleton services services .AddSingleton <ExplorationRegistry>(); // Scoped services services .AddScoped <MetricsPublisher, SimpleMetricsPublisher>(); // Transient Services services .AddTransient <ExplorationScopeBuilder, TypeBasedScopeBuilder>(); // Register Explorer Components services.IncludeRegistry <ComponentRegistry>(); if (Environment.IsDevelopment()) { services.AddCors(options => options.AddDefaultPolicy(b => b.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin())); } }
public void ConfigureContainer(ServiceRegistry services) { // Supports ASP.Net Core DI abstractions services.AddLogging(); services.AddControllers(); // Also exposes Lamar specific registrations // and functionality services.Scan(s => { s.TheCallingAssembly(); s.Assembly(typeof(AppDbContext).Assembly); s.WithDefaultConventions(); }); services.AddDbContext <AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SQLConnection"))); services.AddCors(); // This adds Lamar's validation to the // Oakton.AspNetCore environment check support services.CheckLamarConfiguration(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureContainer(ServiceRegistry services) { services.AddCors(options => { options.AddPolicy(name: AllowDevCors, builder => { builder.WithOrigins("http://localhost:3000"); }); }); services.AddControllersWithViews(); services.IncludeRegistry <WebRegistry>(); services.AddHostedService <RabbitService>(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "ConsumerModul.GitLab - NextPipe Module - Beta API", Version = "v1" }); }); services.AddSpaStaticFiles(conf => { conf.RootPath = "ClientApp/build"; }); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureContainer(ServiceRegistry services) { services.AddMiniProfiler(opt => { // opt.RouteBasePath = "/profiler"; opt.ShouldProfile = _ => true; opt.ShowControls = true; opt.StackMaxLength = short.MaxValue; opt.PopupStartHidden = false; opt.PopupShowTrivial = true; opt.PopupShowTimeWithChildren = true; }); services.AddHttpsRedirection(options => options.HttpsPort = 443); // If environment is localhost, then enable CORS policy, otherwise no cross-origin access services.AddCors(options => options.AddPolicy("CorsPolicy", builder => builder .WithOrigins(_configuration.GetSection("TrustedSpaUrls").Get <string[]>()) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials())); // Add framework services // Add functionality to inject IOptions<T> services.AddOptions(); services.AddResponseCompression(); services.Configure <JwtSettings>(_configuration.GetSection("JwtSettings")); services.AddLogging(); services.AddRouting(options => options.LowercaseUrls = true); if (_env.IsDevelopment()) { services.AddDistributedMemoryCache(); } else { var redisConnectionString = ConnectionStringUrlToRedisResource(_configuration.GetValue <string>("REDISTOGO_URL")); services.AddStackExchangeRedisCache(c => c.Configuration = redisConnectionString); } services.AddSession(options => { // Set a short timeout for easy testing. options.IdleTimeout = TimeSpan.FromMinutes(60); options.Cookie.HttpOnly = true; options.Cookie.Name = ApiConstants.AuthenticationSessionCookieName; options.Cookie.SecurePolicy = CookieSecurePolicy.None; }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Stream-Ripper-API", Version = "v1" }); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); if (File.Exists(xmlPath)) { c.IncludeXmlComments(xmlPath); } c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme.", Type = SecuritySchemeType.Http, Scheme = "bearer" }); }); services.AddMvc(x => { x.ModelValidatorProviders.Clear(); // Not need to have https x.RequireHttpsPermanent = false; // Allow anonymous for localhost if (_env.IsDevelopment()) { x.Filters.Add <AllowAnonymousFilter>(); } // Exception filter attribute x.Filters.Add <ExceptionFilterAttribute>(); }).AddNewtonsoftJson(x => { x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }) .AddRazorPagesOptions(x => x.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute())); services.AddDbContext <EntityDbContext>(opt => { if (_env.IsDevelopment()) { opt.UseSqlite(_configuration.GetValue <string>("ConnectionStrings:Sqlite")); } else { var postgresConnectionString = ConnectionStringUrlToPgResource(_configuration.GetValue <string>("DATABASE_URL") ?? throw new Exception("DATABASE_URL is null")); opt.UseNpgsql(postgresConnectionString); } }); services.AddIdentity <User, IdentityRole <int> >(x => x.User.RequireUniqueEmail = true) .AddEntityFrameworkStores <EntityDbContext>() .AddRoles <IdentityRole <int> >() .AddDefaultTokenProviders(); // L2 EF cache if (_env.IsDevelopment()) { services.AddEFSecondLevelCache(options => options.UseEasyCachingCoreProvider("memory").DisableLogging(true) ); services.AddEasyCaching(options => options.UseInMemory("memory")); } else { services.AddEFSecondLevelCache(options => options.UseEasyCachingCoreProvider("redis").DisableLogging(true)); services.AddEasyCaching(options => { var(_, dictionary) = UrlUtility.UrlToResource(_configuration.GetValue <string>("REDISTOGO_URL")); // use memory cache with your own configuration options.UseRedis(x => { x.DBConfig.Endpoints.Add( new EasyCaching.Core.Configurations.ServerEndPoint(dictionary["Host"], int.Parse(dictionary["Port"]))); x.DBConfig.Username = dictionary["Username"]; x.DBConfig.Password = dictionary["Password"]; x.DBConfig.AbortOnConnectFail = false; }); }); } services.AddEfRepository <EntityDbContext>(x => { x.Profiles(Assembly.Load("Dal"), Assembly.Load("Models")); }); var jwtSetting = _configuration .GetSection("JwtSettings") .Get <JwtSettings>(); if (_env.IsDevelopment() && string.IsNullOrEmpty(jwtSetting.Key)) { jwtSetting.Key = "DCk2T4guOWvu8WRklEEmKazH5gqUJQnyCYXfzFJQU84tY0iJFeUJc2yIQqkqJ4od8AQvyXdlOFP0Q0QGWzB84W4hWFptL8APynvt"; IdentityModelEventSource.ShowPII = true; } services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(config => { config.RequireHttpsMetadata = false; config.SaveToken = true; config.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = jwtSetting.Issuer, ValidAudience = jwtSetting.Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSetting.Key)) }; }); services.For <JwtSettings>().Use(jwtSetting).Singleton(); // If environment is localhost then use mock email service if (_env.IsDevelopment()) { services.For <IS3Service>().Use(new S3Service()).Singleton(); } else { var(accessKeyId, secretAccessKey, url) = ( _configuration.GetRequiredValue <string>("CLOUDCUBE_ACCESS_KEY_ID"), _configuration.GetRequiredValue <string>("CLOUDCUBE_SECRET_ACCESS_KEY"), _configuration.GetRequiredValue <string>("CLOUDCUBE_URL") ); var prefix = new Uri(url).Segments.GetValue(1)?.ToString(); const string bucketName = "cloud-cube"; // Generally bad practice var credentials = new BasicAWSCredentials(accessKeyId, secretAccessKey); // Create S3 client services.For <IAmazonS3>().Use(new AmazonS3Client(credentials, RegionEndpoint.USEast1)); services.For <S3ServiceConfig>().Use(new S3ServiceConfig(bucketName, prefix)); services.For <IS3Service>().Use(ctx => new S3Service( ctx.GetInstance <ILogger <S3Service> >(), ctx.GetInstance <IAmazonS3>(), ctx.GetInstance <S3ServiceConfig>() )); } // Register stuff in container, using the StructureMap APIs... services.Scan(_ => { _.AssemblyContainingType(typeof(Startup)); _.Assembly("Api"); _.Assembly("Logic"); _.Assembly("Dal"); _.WithDefaultConventions(); }); }
public void ConfigureContainer(ServiceRegistry services) { services.AddLogging(config => { config.ClearProviders(); config.AddConfiguration(Configuration.GetSection("Logging")); config.AddApplicationInsights(); }); //Response Compression - https://docs.microsoft.com/en-us/aspnet/core/performance/response-compression?view=aspnetcore-5.0 services.AddResponseCompression(); services.AddCors(options => { options.AddPolicy("SpecificOrigins", builder => { builder.WithOrigins("https://tmireact.azurewebsites.net", "https://theminiindex.com", "https://wwww.theminiindex.com", "http://localhost:3000") .AllowAnyHeader() .AllowAnyMethod(); }); }); services.Configure <CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddSwaggerGen(); services.AddDefaultIdentity <IdentityUser>() .AddRoles <IdentityRole>() .AddEntityFrameworkStores <MiniIndexContext>(); services.AddHangfire(configuration => configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage(Configuration.GetConnectionString("HangfireConnection"), new SqlServerStorageOptions { CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true, DisableGlobalLocks = true })); services.AddHangfireServer(); services .AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddRazorOptions(ConfigureRazor); services.AddDbContext <MiniIndexContext>(ConfigureEntityFramework); string facebookAppId = Configuration["Authentication:Facebook:AppId"]; string facebookAppSecret = Configuration["Authentication:Facebook:AppSecret"]; if (facebookAppId != null && facebookAppSecret != null) { services.AddAuthentication() .AddFacebook(facebookOptions => { facebookOptions.AppId = facebookAppId; facebookOptions.AppSecret = facebookAppSecret; }); } services.AddTransient <IEmailSender, EmailSender>(); services.Configure <AuthMessageSenderOptions>(Configuration); services.AddApplicationInsightsTelemetry(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton <ITelemetryInitializer, TelemetryEnrichment>(); services.AddApplicationInsightsTelemetryProcessor <AppInsightsFilter>(); services.Configure <AzureStorageConfig>(Configuration.GetSection("AzureStorageConfig")); services.IncludeRegistry <CoreServices>(); services.IncludeRegistry <WebAppServices>(); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureContainer(ServiceRegistry services) { services = ConfigureAdditionalServices(services); services.AddCors(options => options.AddPolicy(CorsPolicy, builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .WithExposedHeaders("X-Authorization") )); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); //services.AddSingleton<IAuthorizationHandler, PermissionRequirementHandler>(); services.AddSingleton(provider => Configuration); /*services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) * .AddJwtBearer(options => * { * var authority = $"https://cognito-idp.us-east-1.amazonaws.com/{AWSCognitoSettings.UserPoolId}"; * var audience = AWSCognitoSettings.UserPoolClientId; * * options.Audience = audience; * options.Authority = authority; * options.TokenValidationParameters = new TokenValidationParameters * { * ValidateIssuer = true, * ValidateAudience = false, * ValidateLifetime = true, * ValidateIssuerSigningKey = true, * ValidIssuer = authority, * ValidAudience = audience, * IssuerSigningKey = new CognitoSigningKey(AWSCognitoSettings.UserPoolClientSecret).ComputeKey() * }; * }); * * services.AddAuthorizationCore(options => * { * foreach (var value in EnumExtensions.GetValues<Permissions>()) * { * options.AddPolicy(value.ToString(), policy => policy.Requirements.Add(value.ToRequirement())); * } * * });*/ services.AddControllers(options => { options.Filters.Add(new RequestFilter()); options.Filters.Add(new ResponseFilter()); options.Filters.Add(new CustomExceptionFilter(services.BuildServiceProvider().GetService <ILogger <CustomExceptionFilter> >())); options.ModelBinderProviders.Insert(0, new DateTimeModelBinderProvider()); }) .AddNewtonsoftJson(x => { x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; x.SerializerSettings.Converters.Add(new CustomStringToEnumConverter()); x.SerializerSettings.Converters.Add(new DateTimeConverter()); }); services.AddSwaggerGen(c => { CreateSwaggerGenOptions(c, Assembly.GetEntryAssembly()); var xmlFile = $"{Assembly.GetEntryAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); if (xmlPath != null && File.Exists(xmlPath)) { c.IncludeXmlComments(xmlPath); } }); services.AddSwaggerGenNewtonsoftSupport(); }