public static void AddHangfireServices(this IServiceCollection services, IConfiguration configuration)
        {
            //StackOverflow post on how to register hangfire with mongo:
            //https://stackoverflow.com/questions/58340247/how-to-use-hangfire-in-net-core-with-mongodb

            MongoSettings mongoSettings = new();

            configuration.GetSection(nameof(MongoSettings)).Bind(mongoSettings);

            var migrationOptions = new MongoMigrationOptions
            {
                MigrationStrategy = new MigrateMongoMigrationStrategy(),
                BackupStrategy    = new CollectionMongoBackupStrategy()
            };

            services.AddHangfire(config =>
            {
                config.SetDataCompatibilityLevel(CompatibilityLevel.Version_170);
                config.UseSimpleAssemblyNameTypeSerializer();
                config.UseRecommendedSerializerSettings();
                config.UseMongoStorage(mongoSettings.ConnectionString, mongoSettings.Database, new MongoStorageOptions {
                    MigrationOptions = migrationOptions
                });
            });
            services.AddHangfireServer();
        }
Esempio n. 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHangfire(x => {
                var migrationOptions = new MongoMigrationOptions
                {
                    Strategy       = MongoMigrationStrategy.Migrate,
                    BackupStrategy = MongoBackupStrategy.Collections
                };
                x.UseMongoStorage(Configuration["Mongodb:ConnectString"], "hangfire", new MongoStorageOptions {
                    Prefix = "hangfire", MigrationOptions = migrationOptions
                });
            });
            services.AddHangfireServer();

            //注入配置信息(appsettings.json)
            services.AddSingleton <IConfiguration>(Configuration);
            services.AddMemoryCache();

            services.AddSingleton <INotify, SmsHelper>();

            ///注入顺序不能变
            services.AddSingleton <CurtainHelper>();
            services.AddSingleton <HvacHelper>();
            services.AddSingleton <LightHelper>();
            services.AddSingleton <SensorHelper>();

            services.AddHostedService <MqttHelper>();
            services.AddHostedService <CurtainListener>();
            services.AddHostedService <SwitchListener>();
            services.AddHostedService <SensorListener>();
            services.AddHostedService <HvacListener>();

            services.AddHostedService <SmartService>();


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title   = "Tcp Web Gateway", Version = "v1", Description = "与tcp网关进行通信,并提供api控制设备,支持mqtt",
                    Contact = new Contact
                    {
                        Name  = "Rafael Luo",
                        Email = "*****@*****.**",
                        Url   = "https://www.ivilson.com",
                    }
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });
        }
Esempio n. 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            var mongoConnection  = Configuration.GetConnectionString("HangfireConnection");
            var migrationOptions = new MongoMigrationOptions
            {
                Strategy       = MongoMigrationStrategy.Drop,
                BackupStrategy = MongoBackupStrategy.Collections
            };

            // Add Hangfire services.
            services.AddHangfire(config =>
            {
                config.SetDataCompatibilityLevel(CompatibilityLevel.Version_170);
                config.UseSimpleAssemblyNameTypeSerializer();
                config.UseRecommendedSerializerSettings();
                config.UseMongoStorage(new MongoClient(mongoConnection), "Hangfire", new MongoStorageOptions
                {
                    MigrationOptions = migrationOptions,
                    CheckConnection  = false,
                });
            });

            // SQL settings
            //.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,
            //    UsePageLocksOnDequeue = true,
            //    DisableGlobalLocks = true
            //}));

            services.AddTransient <IProcessService, ProcessService>();

            // https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-2.2&tabs=visual-studio#jsonnet-support
            services.AddControllers().AddNewtonsoftJson();

            // Add the processing server as IHostedService
            services.AddHangfireServer();

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "My API", Version = "v1"
                });
            });
        }
        public void ConfigureServices(IServiceCollection services)
        {
            var migrationOptions = new MongoMigrationOptions
            {
                MigrationStrategy = new MigrateMongoMigrationStrategy(),
                BackupStrategy    = new CollectionMongoBackupStrategy()
            };

            services.AddHangfire(options => options.UseSqlServerStorage(Configuration.GetConnectionString("default")));
            services.AddHangfireServer();

            services.AddControllers();
        }
Esempio n. 5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            // AutoMapper config
            services.AddAutoMapper();

            // Hangfire config
            var hangfireMigrationOptions = new MongoMigrationOptions
            {
                Strategy       = MongoMigrationStrategy.Drop,
                BackupStrategy = MongoBackupStrategy.Collections
            };
            var hangfireStorageOptions = new MongoStorageOptions
            {
                // The time interval after which Hangfire will re-enqueue aborted or failed jobs if the server dies unexpectedly
                InvisibilityTimeout = TimeSpan.FromMinutes(1),
                MigrationOptions    = hangfireMigrationOptions
            };

            services.AddHangfire(configuration =>
            {
                configuration.UseMongoStorage(
                    DbMongoService.MongoDbConnection,
                    DbMongoService.MongoDbHangfireName,
                    hangfireStorageOptions
                    );
            });

            // Services
            services.AddScoped <IDbMongoService, DbMongoService>();
            services.AddScoped <IHostedService, HostedStartupService>();
            services.AddTransient <IHttpService, HttpService>();
            services.AddScoped <ILoggerService, LoggerService>();

            // Clients
            services.AddScoped <HttpClient>();
            services.AddScoped <IProjectClient, ProjectClient>();
            services.AddScoped <IMetadataClient, MetadataClient>();
            services.AddScoped <IScenarioClient, ScenarioClient>();
            services.AddScoped <IResultConfigClient, ResultConfigClient>();
            services.AddScoped <ISimPlanClient, SimPlanClient>();
            services.AddScoped <ISimRunClient, SimRunClient>();
            services.AddScoped <IResultDataClient, ResultDataClient>();
            services.AddScoped <IMarkSessionRepository, MarkSessionRepository>();

            // Handlers
            services.AddScoped <IMarkSessionHandler, MarkSessionHandler>();
            services.AddScoped <IDependantResourceHandler, DependantResourceHandler>();
            services.AddScoped <IBackgroundJobsHandler, BackgroundJobsHandler>();
        }
Esempio n. 6
0
        public void ConfigureServices(IServiceCollection services)
        {
            var migrationOptions = new MongoMigrationOptions
            {
                Strategy       = MongoMigrationStrategy.Migrate,
                BackupStrategy = MongoBackupStrategy.Collections
            };
            var storageOptions = new MongoStorageOptions
            {
                MigrationOptions = migrationOptions
            };

            services.AddHangfire(configuration => configuration.UseMongoStorage("mongodb://localhost:27017", "Hangfire", storageOptions));
        }
Esempio n. 7
0
        public static void ConfigureHangfire(this IServiceCollection services)
        {
            var migrationOptions = new MongoMigrationOptions
            {
                MigrationStrategy = new MigrateMongoMigrationStrategy(),
                BackupStrategy    = new CollectionMongoBackupStrategy()
            };
            var storageOptions = new MongoStorageOptions
            {
                MigrationOptions = migrationOptions
            };

            services.AddHangfire(x =>
                                 x.UseMongoStorage(Settings.MongoConnectionString, "Hangfire", storageOptions));
        }
Esempio n. 8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddScoped <RepetitionAddedEventHandler>();
            services.AddMassTransit(c =>
            {
                c.AddConsumer <RepetitionAddedEventHandler>();
            });

            services.AddSingleton(provider => Bus.Factory.CreateUsingRabbitMq(
                                      cfg =>
            {
                var host = cfg.Host(new Uri(this.Configuration.GetValue <string>("rabbitMQ")), z => { });

                cfg.ReceiveEndpoint(host, "web-service-endpoint2", e =>
                {
                    e.PrefetchCount = 16;
                    e.LoadFrom(provider);
                    EndpointConvention.Map <RepetitionAddedEventHandler>(e.InputAddress);
                });
            }));

            services.AddSingleton <IBus>(provider => provider.GetRequiredService <IBusControl>());
            services.AddSingleton <IHostedService, BusService>();
            services.AddSingleton <IMongoClient>(new MongoClient(this.Configuration.GetValue <string>("mongoConnectionString")));
            services.AddTransient <DailyRepsCounterRepository>();
            services.AddTransient <IRaportService, RaportService>();
            services.AddTransient <SmsService>();

            var migrationOptions = new MongoMigrationOptions
            {
                Strategy       = MongoMigrationStrategy.Migrate,
                BackupStrategy = MongoBackupStrategy.Collections
            };
            var storageOptions = new MongoStorageOptions
            {
                MigrationOptions = migrationOptions,
                CheckConnection  = false
            };

            services.AddHangfire(config =>
            {
                config.UseMongoStorage(this.Configuration.GetValue <string>("mongoConnectionString"), "hangfire", storageOptions);
            });
            services.AddHangfireServer();
        }
Esempio n. 9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var migrationOptions = new MongoMigrationOptions
            {
                Strategy       = MongoMigrationStrategy.Migrate,
                BackupStrategy = MongoBackupStrategy.Collections
            };
            var storageOptions = new MongoStorageOptions
            {
                MigrationOptions = migrationOptions
            };

            services.Configure <IdionlineSettings>(this.Configuration.GetSection("IdionlineSettings"));
            services.AddHangfire(options => options.UseMongoStorage("mongodb://localhost", "IdionlineDB", storageOptions));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);
            services.AddHttpClient();
            services.AddTransient <DataAccess>();
        }
Esempio n. 10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = Configuration.GetConnectionString("Default");
            var dbName           = Configuration.GetValue <string>("MongoDbName");

            // Dependency Injection
            services.AddSingleton <IDbContext, NotifierDb>(
                context => new NotifierDb(connectionString, dbName)
                );
            services.AddSingleton <ISmsGateway, TwilioSmsGateway>();
            services.AddSingleton <ISchedulerGateway, HangFireSchedulerGateway>();
            services.AddSingleton <IRepositoryGateway <string, Message>, MessageRepository>();
            services.AddSingleton <IRepositoryGateway <string, Community>, CommunityRepository>();

            UseCaseInjection(services);


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // Swagger
            services.AddSwaggerDocument();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Notifier Api", Version = "v1"
                });
            });

            // Hangfire services
            var migrationOptions = new MongoMigrationOptions()
            {
                Strategy = MongoMigrationStrategy.Drop
            };

            services.AddHangfire(
                configuration => configuration
                .UseMongoStorage(
                    connectionString,
                    dbName,
                    new MongoStorageOptions {
                MigrationOptions = migrationOptions
            })
                );
        }
        // 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 ConfigureServices(IServiceCollection services)
        {
            services.Configure <MorphicSettings>(Configuration.GetSection("MorphicSettings"));
            services.AddSingleton <MorphicSettings>(serviceProvider => serviceProvider.GetRequiredService <IOptions <MorphicSettings> >().Value);
            services.Configure <DatabaseSettings>(Configuration.GetSection("DatabaseSettings"));
            services.AddSingleton <DatabaseSettings>(serviceProvider => serviceProvider.GetRequiredService <IOptions <DatabaseSettings> >().Value);
            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));
            services.AddSingleton <EmailSettings>(serviceProvider => serviceProvider.GetRequiredService <IOptions <EmailSettings> >().Value);
            services.Configure <KeyStorageSettings>(Configuration.GetSection("KeyStorageSettings"));
            services.AddSingleton <KeyStorageSettings>(serviceProvider => serviceProvider.GetRequiredService <IOptions <KeyStorageSettings> >().Value);
            services.AddSingleton <KeyStorage>(serviceProvider => KeyStorage.CreateShared(serviceProvider.GetRequiredService <KeyStorageSettings>(), serviceProvider.GetRequiredService <ILogger <KeyStorage> >()));
            services.AddSingleton <Plans>(serviceProvider => Plans.FromJson(Path.Join(serviceProvider.GetRequiredService <IWebHostEnvironment>().ContentRootPath, "Billing", serviceProvider.GetRequiredService <StripeSettings>().Plans)));
            services.Configure <StripeSettings>(Configuration.GetSection("StripeSettings"));
            services.AddSingleton <StripeSettings>(serviceProvider => serviceProvider.GetRequiredService <IOptions <StripeSettings> >().Value);
            services.AddSingleton <IPaymentProcessor, StripePaymentProcessor>();
            services.AddSingleton <Database>();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <IRecaptcha, Recaptcha>();
            services.AddSingleton <IBackgroundJobClient, BackgroundJobClient>();
            services.AddRouting();
            services.AddEndpoints();

            var migrationOptions = new MongoMigrationOptions
            {
                Strategy       = MongoMigrationStrategy.Migrate,
                BackupStrategy = MongoBackupStrategy.Collections
            };

            services.AddHangfire(configuration => configuration
                                 .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                                 .UseSimpleAssemblyNameTypeSerializer()
                                 .UseRecommendedSerializerSettings()
                                 .UseSerilogLogProvider()
                                 .UseFilter(new HangfireJobMetrics())
                                 .UseMongoStorage(Configuration.GetSection("HangfireSettings")["ConnectionString"], // TODO Is there a better way than GetSection[]?
                                                  new MongoStorageOptions
            {
                MigrationOptions = migrationOptions
            })
                                 );
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            var migrationOptions = new MongoMigrationOptions {
                Strategy       = MongoMigrationStrategy.Drop,
                BackupStrategy = MongoBackupStrategy.Collections
            };
            var storageOptions = new MongoStorageOptions {
                MigrationOptions = migrationOptions
            };

            GlobalConfiguration.Configuration
            .UseColouredConsoleLogProvider(Hangfire.Logging.LogLevel.Error)
            .UseMongoStorage("mongodb://localhost", "ApplicationDatabase", storageOptions);
            int Cnt = 10;

            for (int i = 0; i < Cnt; i++)
            {
                BackgroundJob.Enqueue <AwesomeTask>(x => x.Execute($"task #{i}", null));
                Console.WriteLine($"Enqueued task#{i}");
            }
        }
Esempio n. 13
0
        private void StartHangfireServer(IContainer container)
        {
            var logProvider = new LykkeLogProvider(container.Resolve <ILogFactory>());

            var migrationOptions = new MongoMigrationOptions
            {
                Strategy       = MongoMigrationStrategy.Migrate,
                BackupStrategy = MongoBackupStrategy.Collections
            };
            var storageOptions = new MongoStorageOptions
            {
                MigrationOptions = migrationOptions
            };

            GlobalConfiguration.Configuration.UseMongoStorage(
                _settings.Db.MongoConnString,
                "NeoClaimTransactionsExecutor", storageOptions);
            GlobalConfiguration.Configuration.UseLogProvider(logProvider)
            .UseAutofacActivator(container);

            container.Resolve <BackgroundJobServer>();
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <AppSettings>(Configuration);

            services
            .AddControllers()
            .AddNewtonsoftJson();

            services.AddMvc();
            services.AddTelegramBot(Configuration);
            services.AddCommandHandlingDependencies <Message, IEnumerable <HandlerResult> >();
            services.AddDataDependencies();
            services.AddServicesDependencies();
            services.AddMonitoringDependencies();

            services.AddTransient <IMainCommandHandler, CommandHandler>();

            var migrationOptions = new MongoMigrationOptions
            {
                Strategy       = MongoMigrationStrategy.Migrate,
                BackupStrategy = MongoBackupStrategy.Collections
            };

            var storageOptions = new MongoStorageOptions
            {
                CheckConnection  = false,
                MigrationOptions = migrationOptions
            };

            services.AddHangfire(config =>
            {
                config.UseMongoStorage(Configuration["DatabaseConnectionString"], Configuration["DatabaseName"], storageOptions);
            });
            services.AddHangfireServer();

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console(new RenderedCompactJsonFormatter())
                         .CreateLogger();
        }
Esempio n. 15
0
        public void ConfigureServices(IServiceCollection services)
        {
            //add Hangfire monitor service with mongodb
            services.AddHangfire(config =>
            {
                var migrationOptions = new MongoMigrationOptions
                {
                    Strategy       = MongoMigrationStrategy.Drop,
                    BackupStrategy = MongoBackupStrategy.Collections
                };
                var storageOptions = new MongoStorageOptions
                {
                    MigrationOptions = migrationOptions
                };

                config.UseMongoStorage(Configuration.GetConnectionString("HangfireDatabase"), storageOptions);
            });

            services.AddHangfireServer();

            services.AddControllers();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);
        }
Esempio n. 16
0
        public static IServiceCollection SetupHangFire(
            this IServiceCollection services,
            IConfiguration configuration)
        {
            var migrationOptions = new MongoMigrationOptions
            {
                Strategy       = MongoMigrationStrategy.Drop,
                BackupStrategy = MongoBackupStrategy.Collections
            };

            services.AddHangfireServer();

            return(services.AddHangfire(config =>
            {
                config.SetDataCompatibilityLevel(CompatibilityLevel.Version_170);
                config.UseSimpleAssemblyNameTypeSerializer();
                config.UseRecommendedSerializerSettings();
                config.UseMongoStorage(configuration.GetSection("MongoDbConnectionString")
                                       .GetSection("HangFireConnection").Value, new MongoStorageOptions {
                    MigrationOptions = migrationOptions
                });
            }));
        }
Esempio n. 17
0
        public void Configuration(IAppBuilder app)
        {
            var migrationOptions = new MongoMigrationOptions
            {
                Strategy       = MongoMigrationStrategy.Migrate,
                BackupStrategy = MongoBackupStrategy.Collections
            };
            var storageOptions = new MongoStorageOptions
            {
                MigrationOptions = migrationOptions
            };

            GlobalConfiguration.Configuration
            .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
            .UseSimpleAssemblyNameTypeSerializer()
            .UseRecommendedSerializerSettings()
            .UseMongoStorage("mongodb://localhost", "Hangfirewithmongodb", storageOptions);     //Hangfirewithmongodb => Database ismi

            app.UseHangfireServer();
            app.UseHangfireDashboard();

            BackgroundJob.Enqueue(() => Baslangic());                   //Başlangıçta tek sefer çalışacak iş parçacığı
            RecurringJob.AddOrUpdate(() => Dakikalik(), Cron.Minutely); //Her dakika çalışacak iş parçacığı
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // enable in-memory caching
            services.AddMemoryCache();

            services.AddMvc(options =>
            {
                // if we ever get to 50 Model Validation errors, ignore subsequent ones
                // more on this here https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.2#top-level-node-validation
                options.MaxModelValidationErrors = 50;
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Thrive Church Official 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);
                c.IncludeXmlComments(xmlPath);
                c.DescribeAllEnumsAsStrings();
            });

            // Preserve Casing of JSON Objects
            services.AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
            .AddJsonOptions(options => options.SerializerSettings.Converters.Add(new StringEnumConverter()));

            // Add functionality to inject IOptions<T>
            services.AddOptions();

            #region Rate Limiting

            // load configuration from appsettings.json
            services.Configure <IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));

            // load IP rules from appsettings.json
            services.Configure <IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies"));

            // inject counter and rules stores
            services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>();
            services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();

            #endregion

            #region File Logging

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.Console()
                         .WriteTo.File("C:/logs/logfile.log", rollingInterval: RollingInterval.Day)
                         .CreateLogger();

            #endregion

            // Add our Config object so it can be injected later
            services.Configure <AppSettings>(options => Configuration.GetSection("EsvApiKey").Bind(options));
            services.Configure <AppSettings>(options => Configuration.GetSection("MongoConnectionString").Bind(options));
            services.Configure <AppSettings>(options => Configuration.GetSection("OverrideEsvApiKey").Bind(options));
            services.Configure <AppSettings>(options => Configuration.GetSection("EmailPW").Bind(options));

            services.AddSingleton(Configuration);

            // Manually register DI dependencies
            services.AddTransient(typeof(ISermonsService), typeof(SermonsService));
            services.AddTransient(typeof(IPassagesRepository), typeof(PassagesRepository));
            services.AddTransient(typeof(ISermonsRepository), typeof(SermonsRepository));
            services.AddTransient(typeof(IPassagesService), typeof(PassagesService));
            services.AddTransient(typeof(IConfigService), typeof(ConfigService));
            services.AddTransient(typeof(IConfigRepository), typeof(ConfigRepository));

            #region Hangfire Tasks

            var hangfireMigrationOptions = new MongoMigrationOptions
            {
                Strategy       = MongoMigrationStrategy.Migrate,
                BackupStrategy = MongoBackupStrategy.Collections
            };

            var hangfireStorageOptions = new MongoStorageOptions
            {
                MigrationOptions = hangfireMigrationOptions
            };

            // Add framework services.
            services.AddHangfire(config =>
            {
                config.UseMongoStorage(Configuration["HangfireConnectionString"], hangfireStorageOptions);
            });

            #endregion
        }
Esempio n. 19
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 ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            services.AddTransient <RequestPopulatorActionFilter>();
            services.AddMvc(config => config.Filters.AddService <RequestPopulatorActionFilter>());

            services.AddOptions();

            services.AddHttpClient <HttpGithubService>(c =>
            {
                c.BaseAddress = new Uri(Configuration["GithubApi:Uri"]);

                if (!string.IsNullOrEmpty(Configuration["GithubApi:UserAgent"]))
                {
                    c.DefaultRequestHeaders.Add("User-Agent", Configuration["GithubApi:UserAgent"]);
                }

                if (!string.IsNullOrEmpty(Configuration["GithubApi:Token"]))
                {
                    c.DefaultRequestHeaders.Add("Authorization", $"token {Configuration["GithubApi:Token"]}");
                }
            });

            services.AddScoped <DeveloperDomain>();

            services.AddHttpClient <HttpGithubService>();
            services.AddScoped <IGithubService>(ctx => ctx.GetService <HttpGithubService>());
            services.AddTransient <IUserService, UserService>();
            services.AddTransient <IDeveloperRepository, MgDeveloperRepository>();

            //adding mediatR dependencies
            services.AddMediatR(Assembly.GetExecutingAssembly());

            //configuring options for MongoDb
            services.Configure <MongoDbOptions>(opts =>
            {
                opts.ConnectionString = Configuration.GetConnectionString("Mongo");
                opts.Database         = Configuration["MongoDb:Database"];
            });

            //adding MongoDb mapping
            BsonClassMap.RegisterClassMap <Developer>(cm =>
            {
                cm.MapProperty(x => x.Avatar).SetIgnoreIfNull(true);
                cm.MapProperty(x => x.Bio);
                cm.MapProperty(x => x.Deslikes);
                cm.MapProperty(x => x.GithubUri);
                cm.MapProperty(x => x.Likes);
                cm.MapProperty(x => x.Name);
                cm.MapProperty(x => x.Username);

                cm.MapIdProperty(x => x.Id).SetSerializer(IdBsonSerializer.Instance).SetIdGenerator(ObjectIdGenerator.Instance);
            });


            services.Configure <JwtUserOptions>(opts =>
            {
                opts.Secret = Configuration["AppSettings:Secret"];
            });

            var byteSecret = Encoding.ASCII.GetBytes(Configuration["AppSettings:Secret"]);

            services.AddAuthentication(x =>
            {
                x.DefaultScheme          = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(byteSecret),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            using (var scoped = services.BuildServiceProvider(false).CreateScope())
            {
                var mongoOpts = scoped.ServiceProvider.GetService <IOptions <MongoDbOptions> >().Value;

                services.AddHealthChecks()
                .AddGithub(uriOpts =>
                {
                    uriOpts.Uri       = new Uri(Configuration["GithubApi:Uri"]);
                    uriOpts.Token     = Configuration["GithubApi:Token"];
                    uriOpts.UserAgent = Configuration["GithubApi:UserAgent"];
                }, "GithubApi", HealthStatus.Degraded)

                .AddMongoDb(mongoOpts.ConnectionString, "mongo", HealthStatus.Unhealthy);


                // Add framework services.
                services.AddHangfire(config =>
                {
                    var migrationOptions = new MongoMigrationOptions
                    {
                        Strategy       = MongoMigrationStrategy.Drop,
                        BackupStrategy = MongoBackupStrategy.None
                    };
                    var opts = new MongoStorageOptions {
                        Prefix = "hf_", CheckConnection = false, MigrationOptions = migrationOptions
                    };
                    config.UseMongoStorage(mongoOpts.ConnectionString, mongoOpts.Database, opts);
                });
            }

            services.AddHealthChecksUI();

            // Add the processing server as IHostedService
            services.AddHangfireServer();

            services.AddSwaggerGen(opts =>
            {
                opts.SwaggerDoc("v1", new Info()
                {
                    Title = "TinDev App", Version = "v1"
                });

                opts.OperationFilter <SwaggerRemoveCancellationTokenParameterFilter>();
            });

            services.AddFeatureManagement();
        }