Esempio n. 1
0
        // 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()));
            }
        }
Esempio n. 2
0
        public void ConfigureContainer(ServiceRegistry services)
        {
            services.AddSyrfDefaultServices(_configuration);
            services.AddSyrfDataServices(_configuration);
            services.AddSyrfFileService(_configuration);
            services.AddHealthChecks();
            services.AddControllers().AddControllersAsServices();
            services.ConfigureSyrfMassTransit(_configuration, null, (cfg, provider) =>
            {
                cfg.UseCircuitBreaker(cb =>
                {
                    cb.TrackingPeriod  = TimeSpan.FromMinutes(1);
                    cb.TripThreshold   = 15;
                    cb.ActiveThreshold = 10;
                    cb.ResetInterval   = TimeSpan.FromMinutes(5);
                });
                cfg.UseRateLimit(50, TimeSpan.FromSeconds(10));
            });
            services.Configure <HealthCheckPublisherOptions>(options =>
            {
                options.Delay     = TimeSpan.FromSeconds(2);
                options.Predicate = check => check.Tags.Contains("ready");
            });

            services.IncludeRegistry <SyrfRegistry>();
            services.IncludeRegistry <MongoLamarRegistry>();
            services.For <IFileService>().Use <S3FileService>();
        }
Esempio n. 3
0
        public void ConfigureContainer(ServiceRegistry services)
        {
            services.UseNextPipeDefaultConfiguration(Configuration);
            services.AddControllers();
            services.IncludeRegistry <LamarRegistry>();

            services.AddMvc().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
            });

            // in-comment this again to get complete IOC validation
            //var container = new Container(services);
            //container.AssertConfigurationIsValid();
            services.AddHostedService <ArchiveManagerService>();
            services.AddHostedService <ModuleStateManagerService>();
            services.AddHostedService <ResourceAndStateManagerService>();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "NextPipe Beta Core API", Version = "v1"
                });
            });
        }
Esempio n. 4
0
        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();
            });
        }
Esempio n. 5
0
        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.AddDefaultCorrelationId();
            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.AddHttpClient(string.Empty)
            .AddCorrelationIdForwarding();

            services.AddSwagger();
            services.AddHealthChecks().AddCheck <ReadinessCheck>("PROJECT_NAME readiness", tags: new[] { "readiness" });
            services.AddCustomizedLogging();
            services.AddDependencyInjection(Configuration);

            services.AddHealthChecks();
            services.AddControllers()
            .AddJsonOptions(options =>
                            options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
        }
Esempio n. 7
0
 public void ConfigureContainer(ServiceRegistry serviceRegistry)
 {
     serviceRegistry.AddControllers();
     serviceRegistry.AddSwaggerDocument();
     serviceRegistry.IncludeRegistry <CTeleportServiceRegistry>();
     serviceRegistry.AddAuthorization();
 }
Esempio n. 8
0
 // 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.AddHttpClient();
     services.AddSwagger(Configuration);
     services.AddDependencyInjection(Configuration);
     services.AddControllers();
     services.AddHealthChecks();
     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);
     });
 }
Esempio n. 9
0
        public void ConfigureContainer(ServiceRegistry services)
        {
            services.AddControllers();
            services.AddSingleton(Log.Logger);

            services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
            services.AddAWSService <IAmazonS3>();
            services.AddAWSService <IAmazonTextract>();

            services.IncludeRegistry <DocumentAnalyzerServiceRegistry>();
        }
Esempio n. 10
0
        // 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();
        }
Esempio n. 11
0
        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>();
        }
Esempio n. 12
0
        public void ConfigureContainer(ServiceRegistry services)
        {
            // Supports ASP.Net Core DI abstractions
            services.AddAuthorization();
            services.AddControllers()
            .AddControllersAsServices();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "LamarExample", Version = "v1"
                });
            });

            // Also exposes Lamar specific registrations
            // and functionality
            services.Scan(s =>
            {
                // Automatically register services that follow default conventions, e.g.
                // PurchasingService/IPurchasingService
                // ConcreteService (concrete types can always be resolved)
                // Typically, you will have a lot of Service/IService pairs in your app
                s.AssemblyContainingType(typeof(Startup));
                s.WithDefaultConventions();
                // Register all of the implementations of IGamingService
                // CrosswordService
                // SudokuService
                s.AddAllTypesOf <IGamingService>();
                // Register all non-generic implementations of IValidatior<T> (UserModelValidator)
                s.ConnectImplementationsToTypesClosing(typeof(IValidator <>));
            });


            // When a ILeaderboard<T> is requested, use Leaderboard<T>
            // Equivalent to:
            // services.AddTransient(typeof(ILeaderboard<>), typeof(Leaderboard<>));
            services.For(typeof(ILeaderboard <>)).Use(typeof(Leaderboard <>));
            // When an IUnitOfWork<T> is requested, run the lambda
            // Also, has a "scoped" lifetime, instead of the default "transient" lifetime
            // Equivalent to:
            //services.AddScoped<IUnitOfWork>(_ => new UnitOfWork(3));
            services.For <IUnitOfWork>().Use(_ => new UnitOfWork(3)).Scoped();
            // For a given T, when an IValidator<T> is requested,
            // but there are no non-generic implementations of IValidator<T>
            // Use DefaultValidator<T> instead
            // No equivalent using the built-in container
            services.For(typeof(IValidator <>)).Add(typeof(DefaultValidator <>));
        }
Esempio n. 13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureContainer(ServiceRegistry services)
        {
            services.AddDbContext <AuthIdentityDbContext>();

            services
            .AddIdentity <MyIdentityUser, MyIdentityRole>(options => options.SignIn.RequireConfirmedAccount = false)
            .AddEntityFrameworkStores <AuthIdentityDbContext>();;

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "LamarWithIdentityOnNet5", Version = "v1"
                });
            });
        }
Esempio n. 14
0
        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>();
            });
        }
Esempio n. 15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureContainer(ServiceRegistry services)
        {
            services.AddControllers();
            // Also exposes Lamar specific registrations
            // and functionality
            services.Scan(s =>
            {
                s.LookForRegistries();
                s.TheCallingAssembly();
                s.AssembliesAndExecutablesFromApplicationBaseDirectory(a => a.FullName.Contains("CleanArchitecture"));
                s.AssemblyContainingType(typeof(Startup));
                s.WithDefaultConventions();
            });

            services.AddSwaggerDocument();
        }
Esempio n. 16
0
        // Take in Lamar's ServiceRegistry instead of IServiceCollection
        // as your argument, but fear not, it implements IServiceCollection
        // as well
        public void ConfigureContainer(ServiceRegistry services)
        {
            // Supports ASP.Net Core DI abstractions
            services.AddMvc();
            services.AddLogging();

            //for use of apis
            services.AddControllers();

            // Also exposes Lamar specific registrations
            // and functionality
            services.Scan(s =>
            {
                s.TheCallingAssembly();
                s.WithDefaultConventions();
            });
        }
Esempio n. 17
0
        public void ConfigureContainer(ServiceRegistry services)
        {
            Debug.WriteLine("Startup.ConfigureContainer");

            services.AddAutoMapper(typeof(Startup).Assembly);

            services.Scan(
                scanner =>
            {
                scanner.AssembliesFromApplicationBaseDirectory();
                scanner.LookForRegistries();
            });

            RegisterMocks(services);

            services.AddControllers();
        }
Esempio n. 18
0
        public void ConfigureContainer(ServiceRegistry services)
        {
            const string variable = "OPEN_WEATHER_MAP_API_KEY";

            if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable(variable)))
            {
                Environment.SetEnvironmentVariable(variable, "fc28830c17565772df3697a3b91bcd47");
            }

            // It's a good practice to avoid registering the infrastructure layer with the upper layers.
            // This can be done using the method below.
            // https://ardalis.com/avoid-referencing-infrastructure-in-visual-studio-solutions
            //
            //const string name = "Way2.Infrastructure.DependencyResolution.dll";
            //var path = Path.Combine(AppContext.BaseDirectory, name);
            //var assembly = Assembly.LoadFrom(path);
            //services.Scan(_ =>
            //{
            //    _.Assembly(assembly);
            //    _.LookForRegistries();
            //});

            services.AddLamar <InfrastructureRegistry>();

            services.AddControllers();

            services.AddHealthChecks();

            services.AddApiVersioning();

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "API v1", Version = "v1"
                });
                options.OperationFilter <RemoveVersionFromParameter>();
                options.DocumentFilter <ReplaceVersionWithExactValueInPath>();
            });

            services.AddHostedService <DatabaseMigrationHostedService>();
            services.AddHostedService <DatabaseSeedHostedService>();
            services.AddHostedService <WeatherFetcherBackgroundService>();
        }
Esempio n. 19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureContainer(ServiceRegistry services)
        {
            services.AddControllers();

            services.Scan(s =>
            {
                s.TheCallingAssembly();
                s.WithDefaultConventions();
            });

            var assemblies =
                AppDomain
                .CurrentDomain
                .GetAssemblies()
                .Where(s => s.GetName().Name.StartsWith(nameof(Sigantha)))
                .ToArray();

            // Auto Mapper
            services.AddAutoMapper(assemblies);

            // Mediatr
            services.AddMediatR(assemblies);

            services.Scan(scanner =>
            {
                foreach (var assembly in assemblies)
                {
                    scanner.Assembly(assembly);
                }

                scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler <,>));
            });

            // Need to add one for mediatr to see all of them
            services.For <IRequestHandler <TimelineGet.Query, TimelineGet.Result> >().Use <TimelineGet.Handler>();

            services.For <IMediator>().Use <Mediator>().Transient();
            services.For <ServiceFactory>().Use(ctx => ctx.GetInstance);

            // Db Contexts
            services.AddDbContext <SiganthaContext>(ServiceLifetime.Transient);
        }
Esempio n. 20
0
 public virtual void ConfigureContainer(ServiceRegistry services)
 {
     services.AddHealthChecks();
     services.AddControllers().AddControllersAsServices();
     services.ConfigureSyrfMassTransit(_configuration, cfg =>
     {
         cfg.AddSagaStateMachines(Assembly.GetEntryAssembly());
         cfg.AddSagas(Assembly.GetEntryAssembly());
     },
                                       (rabbitMqConfig, provider) => { rabbitMqConfig.UseDelayedExchangeMessageScheduler(); }
                                       );
     services.Configure <HealthCheckPublisherOptions>(options =>
     {
         options.Delay     = TimeSpan.FromSeconds(2);
         options.Predicate = check => check.Tags.Contains("ready");
     });
     services.AddSingleton(_configuration.GetSection("MessageBusConfig")
                           .Get <MessageBusConfig>());
     services.IncludeRegistry <SyrfRegistry>();
 }
Esempio n. 21
0
        // 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()));
            }
        }
Esempio n. 22
0
        public void ConfigureContainer(ServiceRegistry serviceRegistry)
        {
            var logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(Configuration)
                         .CreateLogger();

            logger.Information("Logger has been configured.");
            serviceRegistry.Scan(s =>
            {
                s.TheCallingAssembly();
                s.AssembliesFromApplicationBaseDirectory((assembly) => { return(assembly.FullName.Contains("kyc")); });
                s.AssemblyContainingType <IAlbumsDBContext>();
                s.WithDefaultConventions();
            });
            serviceRegistry.For <ILogger>().Use(logger);
            var mapperConfig = new MapperConfiguration(
                mc => mc.AddProfile(new MapperProfile())
                );

            serviceRegistry.AddSingleton(mapperConfig.CreateMapper());
            serviceRegistry.AddControllers();
            serviceRegistry.AddDbContext <AlbumsDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("AlbumsDBContext")), ServiceLifetime.Transient);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureContainer(ServiceRegistry services)
        {
            services.AddControllers();
            services
            .AddMvc(options => { options.EnableEndpointRouting = false; })
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddControllersAsServices()
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                options.JsonSerializerOptions.IgnoreNullValues = true;
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Sportradar Recruitment Service Api", Version = "v1"
                });
            });

            services.IncludeRegistry <Registry>();
        }
Esempio n. 24
0
 //REMOVED IContainer. It is not needed
 public void ConfigureContainer(ServiceRegistry services)
 {
     //Apply scan to the registry so container is aware of types.
     services.Scan(scanner => {
         scanner.AssembliesAndExecutablesFromApplicationBaseDirectory(a =>
                                                                      a.FullName.Contains("Test3.1"));
         scanner.WithDefaultConventions();
         scanner.SingleImplementationsOfInterface();
     });
     services
     .AddControllers(options => {
         // Disable automatic fallback to JSON
         options.ReturnHttpNotAcceptable = true;
         // Honor browser's Accept header (e.g. Chrome)
         options.RespectBrowserAcceptHeader = true;
     })
     .AddControllersAsServices();
     services.AddMvc()
     .AddControllersAsServices();
     services.WhatDidIScan();
     services.WhatDoIHave();
     Console.Write("Container Instantiated");
 }
Esempio n. 25
0
        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();
        }
Esempio n. 26
0
        // 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();
        }
Esempio n. 27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureContainer(ServiceRegistry services)
        {
            services.AddControllers();

            services.Scan(s =>
            {
                s.TheCallingAssembly();
                s.WithDefaultConventions();
            });

            var assemblies =
                AppDomain
                .CurrentDomain
                .GetAssemblies()
                .Where(s => s.GetName().Name.StartsWith(nameof(Conglomerate)))
                .ToArray();

            // Auto Mapper
            services.AddAutoMapper(assemblies);

            // Services
            services.For <IIngredientService>().Use <IngredientService>();

            // Repositories
            services.For <IIngredientRepository>().Use <IngredientRepository>();

            // Mediatr
            services.AddMediatR(assemblies);

            services.Scan(scanner =>
            {
                foreach (var assembly in assemblies)
                {
                    scanner.Assembly(assembly);
                }

                scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler <,>));
            });

            // For some reason we need to register one of the handlers for Lamar to register all of them
            services.For <IRequestHandler <IngredientGetAll.Query, IList <IngredientGetAll.Ingredient> > >().Use <IngredientGetAll.Handler>();

            services.For <IMediator>().Use <Mediator>().Transient();
            services.For <ServiceFactory>().Use(ctx => ctx.GetInstance);

            // Db Contexts
            services.AddDbContext <SandwichShopContext>(ServiceLifetime.Transient);

            // Hangfire
            services.AddHangfire(configuration => configuration
                                 .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                                 .UseSimpleAssemblyNameTypeSerializer()
                                 .UseRecommendedSerializerSettings()
                                 .UseStorage(new MySqlStorage(Configuration.GetConnectionString("Hangfire"), new MySqlStorageOptions()
            {
                TransactionIsolationLevel  = IsolationLevel.ReadCommitted,
                QueuePollInterval          = TimeSpan.FromSeconds(1),
                JobExpirationCheckInterval = TimeSpan.FromHours(1),
                CountersAggregateInterval  = TimeSpan.FromMinutes(5),
                PrepareSchemaIfNecessary   = true,
                DashboardJobListLimit      = 50000,
                TransactionTimeout         = TimeSpan.FromMinutes(1),
                TablePrefix = "Hangfire"
            })));

            services.AddHangfireServer(options =>
            {
                // Order determines priority
                options.Queues = new[] { JobQueues.API, JobQueues.DEFAULT };
            });

            services.For <IJobFactory>().Use <JobFactory>();
        }