Пример #1
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            // We need to get the app directory this way.  Using Environment.CurrentDirectory doesn't work in Azure
            ExecutionContextOptions executioncontextoptions = builder.Services.BuildServiceProvider()
                                                              .GetService <IOptions <ExecutionContextOptions> >().Value;
            string currentDirectory = executioncontextoptions.AppDirectory;

            IConfigurationBuilder configBuilder = new ConfigurationBuilder()
                                                  .SetBasePath(currentDirectory)
                                                  .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                                                  .AddEnvironmentVariables();

            IConfigurationRoot config = configBuilder.Build();

            // DI doesn't work in startup
            PollyHttpPolicies pollyHttpPolicies = new PollyHttpPolicies(new PollyHttpPoliciesConfig());

            Dictionary <HttpClientConfigName, ApiConfig> httpClientConfigs = config.GetSection("Apis").Get <Dictionary <HttpClientConfigName, ApiConfig> >();

            foreach (KeyValuePair <HttpClientConfigName, ApiConfig> httpClientConfig in httpClientConfigs)
            {
                IAsyncPolicy <HttpResponseMessage> retryPolicy = httpClientConfig.Value.IsExternal ? pollyHttpPolicies.ExternalHttpRetryPolicy : pollyHttpPolicies.InternalHttpRetryPolicy;

                builder.Services.AddHttpClient(httpClientConfig.Key.ToString(), c =>
                {
                    c.BaseAddress = new Uri(httpClientConfig.Value.BaseAddress);

                    c.Timeout = httpClientConfig.Value.Timeout ?? new TimeSpan(0, 0, 0, 15);

                    foreach (KeyValuePair <string, string> header in httpClientConfig.Value.Headers)
                    {
                        c.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                    c.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
                    c.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
                }).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
                {
                    MaxConnectionsPerServer = httpClientConfig.Value.MaxConnectionsPerServer ?? 15,
                    AutomaticDecompression  = DecompressionMethods.GZip | DecompressionMethods.Deflate
                }).AddPolicyHandler(retryPolicy);
            }

            IConfigurationSection emailConfigSettings = config.GetSection("EmailConfig");

            builder.Services.Configure <EmailConfig>(emailConfigSettings);

            IConfigurationSection serviceBusConfigSettings = config.GetSection("ServiceBusConfig");

            builder.Services.Configure <ServiceBusConfig>(serviceBusConfigSettings);
            ServiceBusConfig serviceBusConfig = serviceBusConfigSettings.Get <ServiceBusConfig>();

            IConfigurationSection sendGridConfigSettings = config.GetSection("SendGridConfig");

            builder.Services.Configure <SendGridConfig>(sendGridConfigSettings);
            var sendGridConfig = config.GetSection("SendGridConfig").Get <SendGridConfig>();

            builder.Services.AddSingleton <ISendGridClient>(new SendGridClient(sendGridConfig.ApiKey));

            builder.Services.AddTransient <IHttpClientWrapper, HttpClientWrapper>();
            builder.Services.AddMediatR(typeof(SendEmailHandler).Assembly);
            builder.Services.AddAutoMapper(typeof(AddressDetailsProfile).Assembly);
            builder.Services.AddSingleton <IQueueClient>(new QueueClient(serviceBusConfig.ConnectionString, serviceBusConfig.MessageQueueName));

            builder.Services.AddSingleton <IMessageFactory, MessageFactory>();
            //builder.Services.AddSingleton<IConnectSendGridService, SendGridService>();
            builder.Services.AddSingleton <ISendEmailService, SendEmailService>();
            builder.Services.AddSingleton <IConnectUserService, ConnectUserService>();
            builder.Services.AddSingleton <IConnectRequestService, ConnectRequestService>();
            builder.Services.AddSingleton <IConnectGroupService, ConnectGroupService>();
            builder.Services.AddTransient <IJobFilteringService, JobFilteringService>();
            builder.Services.AddSingleton <IConnectAddressService, ConnectAddressService>();
            builder.Services.AddSingleton <IConnectSendGridService, ConnectSendGridService>();
            builder.Services.AddSingleton <IDistanceCalculator, DistanceCalculator>();
            builder.Services.AddSingleton <IPurgeService, PurgeService>();

            builder.Services.AddDbContext <ApplicationDbContext>(options =>
                                                                 options.UseInMemoryDatabase(databaseName: "CommunicationService.AzureFunction"));
            builder.Services.AddTransient <IRepository, Repository>();

            CosmosConfig cosmosConfig = config.GetSection("CosmosConfig").Get <CosmosConfig>();

            builder.Services.AddSingleton <ICosmosDbService>(InitializeCosmosClientInstance(cosmosConfig));

            InterUserMessageConfig interUserMessageConfig = config.GetSection("InterUserMessageConfig").Get <InterUserMessageConfig>();

            builder.Services.AddSingleton <IInterUserMessageRepository>(InitializeCosmosClientInstance(interUserMessageConfig));

            IConfigurationSection linkConfigSettings = config.GetSection("LinkConfig");

            builder.Services.Configure <LinkConfig>(linkConfigSettings);

            LinkConfig linkConfig = config.GetSection("LinkConfig").Get <LinkConfig>();

            builder.Services.AddSingleton <ILinkRepository>(InitializeCosmosClientInstance(linkConfig));

            SendGridManagement.EmailTemplateUploader emailTemplateUploader =
                new SendGridManagement.EmailTemplateUploader(new SendGridClient(sendGridConfig.ApiKey), InitializeCosmosClientInstance(cosmosConfig));

            builder.Services.AddSingleton <IPollyMemoryCacheProvider, PollyMemoryCacheProvider>();
            builder.Services.AddMemCache();
            builder.Services.AddSingleton(x => x.GetService <IMemDistCacheFactory <LocationDetails> >().GetCache(new TimeSpan(30, 0, 0, 0), ResetTimeFactory.OnMidday));
            builder.Services.AddSingleton(x => x.GetService <IMemDistCacheFactory <Template> >().GetCache(new TimeSpan(30, 0, 0, 0), ResetTimeFactory.OnMidday));
            builder.Services.AddSingleton(x => x.GetService <IMemDistCacheFactory <UnsubscribeGroup> >().GetCache(new TimeSpan(30, 0, 0, 0), ResetTimeFactory.OnMidday));


            emailTemplateUploader.Migrate().ConfigureAwait(false);
        }
Пример #2
0
 public DistributedCachePollyWrapper(IDistributedCache <TKey, TValue> innerCache, IAsyncPolicy policy)
     : this(innerCache, policy, policy, policy, policy, policy)
 {
 }
Пример #3
0
 public static AsyncPolicy GenerateCosmosPolicy(IAsyncPolicy chainedPolicy)
 {
     return(GenerateCosmosPolicy(new[] { chainedPolicy }));
 }
Пример #4
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            // We need to get the app directory this way.  Using Environment.CurrentDirectory doesn't work in Azure.
            ExecutionContextOptions executioncontextoptions = builder.Services.BuildServiceProvider()
                                                              .GetService <IOptions <ExecutionContextOptions> >().Value;
            string currentDirectory = executioncontextoptions.AppDirectory;

            var config = new ConfigurationBuilder()
                         .SetBasePath(currentDirectory)
                         .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                         .AddJsonFile("local.settings.json", true)
                         .AddEnvironmentVariables().Build();

            // DI doesn't work in startup
            PollyHttpPolicies pollyHttpPolicies = new PollyHttpPolicies(new PollyHttpPoliciesConfig());

            Dictionary <HttpClientConfigName, ApiConfig> httpClientConfigs = config.GetSection("Apis").Get <Dictionary <HttpClientConfigName, ApiConfig> >();

            foreach (KeyValuePair <HttpClientConfigName, ApiConfig> httpClientConfig in httpClientConfigs)
            {
                IAsyncPolicy <HttpResponseMessage> retryPolicy = httpClientConfig.Value.IsExternal ? pollyHttpPolicies.ExternalHttpRetryPolicy : pollyHttpPolicies.InternalHttpRetryPolicy;

                builder.Services.AddHttpClient(httpClientConfig.Key.ToString(), c =>
                {
                    c.BaseAddress = new Uri(httpClientConfig.Value.BaseAddress);

                    c.Timeout = httpClientConfig.Value.Timeout ?? new TimeSpan(0, 0, 0, 15);

                    foreach (KeyValuePair <string, string> header in httpClientConfig.Value.Headers)
                    {
                        c.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                    c.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
                    c.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
                }).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
                {
                    MaxConnectionsPerServer = httpClientConfig.Value.MaxConnectionsPerServer ?? int.MaxValue,
                    AutomaticDecompression  = DecompressionMethods.GZip | DecompressionMethods.Deflate
                }).AddPolicyHandler(retryPolicy);
            }

            builder.Services.AddMediatR(typeof(GetUserByIDHandler).Assembly);

            IConfigurationSection connectionStringSettings = config.GetSection("ConnectionStrings");

            builder.Services.Configure <ConnectionStrings>(connectionStringSettings);

            IConfigurationSection applicationConfigSettings = config.GetSection("ApplicationConfig");

            builder.Services.Configure <ApplicationConfig>(applicationConfigSettings);

            var sqlConnectionString = config.GetConnectionString("SqlConnectionString");

            builder.Services.AddDbContext <ApplicationDbContext>(options =>
                                                                 options.UseSqlServer(sqlConnectionString));

            builder.Services.AddTransient <IRepository, Repository>();
            builder.Services.AddTransient <IAddressService, AddressService>();
            builder.Services.AddTransient <ICommunicationService, CommunicationService>();
            builder.Services.AddTransient <IGroupService, GroupService>();
            builder.Services.AddTransient <IHelperService, HelperService>();
            builder.Services.AddTransient <IHttpClientWrapper, HttpClientWrapper>();
            builder.Services.AddTransient <IDistanceCalculator, DistanceCalculator>();
            builder.Services.AddTransient <IVolunteerCache, VolunteerCache>();
            builder.Services.AddTransient <IVolunteersForCacheGetter, VolunteersForCacheGetter>();
            builder.Services.AddSingleton <IPollyMemoryCacheProvider, PollyMemoryCacheProvider>();
            builder.Services.AddTransient <ISystemClock, MockableDateTime>();
            builder.Services.AddTransient <ICoordinatedResetCache, CoordinatedResetCache>();
            builder.Services.AddTransient <IVolunteersFilteredByMinDistanceGetter, VolunteersFilteredByMinDistanceGetter>();
            builder.Services.AddTransient <IMinDistanceFilter, MinDistanceFilter>();

            // add cache
            RedisConfig redisConfig = new RedisConfig();

            config.GetSection("RedisConfig").Bind(redisConfig);
            builder.Services.AddMemDistCache(redisConfig.AppName, redisConfig.ConnectionString);

            builder.Services.AddSingleton <IMemDistCache <IEnumerable <CachedVolunteerDto> > >(x => x.GetService <IMemDistCacheFactory <IEnumerable <CachedVolunteerDto> > >().GetCache(new TimeSpan(7, 0, 0, 0), ResetTimeFactory.OnHour));

            IConfigurationSection firebaseConfigSettings = config.GetSection("FirebaseConfig");

            builder.Services.Configure <FirebaseConfig>(firebaseConfigSettings);
            builder.Services.AddSingleton <IAuthService, AuthService>();

            // automatically apply EF migrations
            DbContextOptionsBuilder <ApplicationDbContext> dbContextOptionsBuilder = new DbContextOptionsBuilder <ApplicationDbContext>();

            dbContextOptionsBuilder.UseSqlServer(sqlConnectionString);
            ApplicationDbContext dbContext = new ApplicationDbContext(dbContextOptionsBuilder.Options);

            dbContext.Database.Migrate();
        }
Пример #5
0
 public StockItemRepository(PetStoreContext context, IAsyncPolicy retryPolicy)
     : base(context, retryPolicy)
 {
 }
 public static Policy GenerateMessagingPolicy(IAsyncPolicy chainedPolicy)
 {
     return(GenerateMessagingPolicy(new[] { chainedPolicy }));
 }
Пример #7
0
 internal AsyncPolicyScopeBase(IServiceProvider serviceProvider, IAsyncPolicy asyncPolicy)
 {
     ServiceProvider = serviceProvider;
     Policy          = asyncPolicy;
 }
Пример #8
0
        private async Task <HttpResponseMessage> SendRequestWithPolicy(IHttpRequestMessageBuilder requestBuilder, IAsyncPolicy <HttpResponseMessage> policy = null, CancellationToken cancellationToken = default)
        {
            HttpRequestMessage request = requestBuilder.Request;

            using (request)
            {
                Func <CancellationToken, Task <HttpResponseMessage> > sendRequest = (ct) => this.httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct);
                if (policy != null)
                {
                    HttpResponseMessage response = await policy.ExecuteAsync(sendRequest, cancellationToken).ConfigureAwait(false);

                    return(response);
                }
                else
                {
                    HttpResponseMessage response = await sendRequest(cancellationToken).ConfigureAwait(false);

                    return(response);
                }
            }
        }
Пример #9
0
 public static RestClientFactory <TResult> Create(IAsyncPolicy <TResult> asyncPolicy)
 {
     return(InstanceRestClient.SetAsyncPolicy(asyncPolicy));
 }
Пример #10
0
        public EventBusRabbitMQ(
            ILoadBalancer <IRabbitMQPersistentConnection> receiveLoadBlancer,
            ILoadBalancer <IRabbitMQPersistentConnection> senderLoadBlancer,
            ILogger <IEventBus> logger,
            IServiceProvider lifetimeScope,
            int reveiverMaxDegreeOfParallelism    = 10,
            int receiverAcquireRetryAttempts      = 0,
            int receiverHandlerTimeoutMillseconds = 5000,
            int senderRetryCount = 3,
            int senderConfirmTimeoutMillseconds = 500,
            ushort preFetch     = 1,
            string exchange     = "amp.topic",
            string exchangeType = "topic")
        {
            this._preFetch     = preFetch;
            this._exchange     = exchange;
            this._exchangeType = exchangeType;


            this._reveiverMaxDegreeOfParallelism = reveiverMaxDegreeOfParallelism;
            this._receiverLoadBlancer            = receiveLoadBlancer;

            this._senderLoadBlancer = senderLoadBlancer;
            this._senderConfirmTimeoutMillseconds = senderConfirmTimeoutMillseconds;

            this._lifetimeScope = lifetimeScope ?? throw new ArgumentNullException(nameof(lifetimeScope));
            this._logger        = logger ?? throw new ArgumentNullException(nameof(logger));

            #region 生产端策略
            this._senderRetryPolicy = Policy.NoOpAsync();//创建一个空的Policy

            this._senderRetryPolicy = _senderRetryPolicy.WrapAsync(Policy.Handle <BrokerUnreachableException>()
                                                                   .Or <SocketException>()
                                                                   .Or <System.IO.IOException>()
                                                                   .Or <AlreadyClosedException>()
                                                                   .WaitAndRetryAsync(senderRetryCount, retryAttempt => TimeSpan.FromMilliseconds(Math.Pow(2, retryAttempt)), (ex, time) =>
            {
                _logger.LogError(ex.ToString());
            }));
            #endregion


            #region 消费者策略
            _receiverPolicy = Policy.NoOpAsync();//创建一个空的Policy

            if (receiverAcquireRetryAttempts > 0)
            {
                //设置重试策略
                _receiverPolicy = _receiverPolicy.WrapAsync(Policy.Handle <Exception>()
                                                            .RetryAsync(receiverAcquireRetryAttempts, (ex, time) =>
                {
                    _logger.LogError(ex, ex.ToString());
                }));
            }

            if (receiverHandlerTimeoutMillseconds > 0)
            {
                // 设置超时
                _receiverPolicy = _receiverPolicy.WrapAsync(Policy.TimeoutAsync(
                                                                TimeSpan.FromMilliseconds(receiverHandlerTimeoutMillseconds),
                                                                TimeoutStrategy.Optimistic,
                                                                (context, timespan, task) =>
                {
                    return(Task.FromResult(true));
                }));
            }
            #endregion
        }
Пример #11
0
 public HttpToDoService(HttpClient http, IAsyncPolicy policy)
 {
     _http   = http;
     _policy = policy;
 }
Пример #12
0
 public RequestSimulator()
 {
     _RedisDatabase      = GetRedisDatabaseConnection().Result;
     _RedisBackoffPolicy = InitializeRedisBackoffPolicy();
 }
Пример #13
0
        public static void RegisterServices(IServiceCollection services, IHostingEnvironment environment, IConfiguration configuration)
        {
            //Data Protection
            var dataProtectionBuilder = services.AddDataProtection()
                                        .SetApplicationName("PipelineSpace")
                                        .SetDefaultKeyLifetime(TimeSpan.FromDays(30));

            if (!environment.IsDevelopment())
            {
                //var redis = ConnectionMultiplexer.Connect(configuration.GetConnectionString("RedisConnection"));
                dataProtectionBuilder
                .PersistKeysToAzureBlobStorage(
                    new CloudBlobContainer(new StorageUri(new Uri(configuration["DataProtection:Storage:ContainerAddress"])),
                                           new StorageCredentials(configuration["DataProtection:Storage:AccountName"], configuration["DataProtection:Storage:KeyValue"], configuration["DataProtection:Storage:KeyName"])), configuration["DataProtection:Storage:BlobName"])
                //.PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys")
                .ProtectKeysWithAzureKeyVault(
                    configuration["DataProtection:AzureKeyVault:KeyIdentifier"],
                    configuration["DataProtection:AzureKeyVault:ClientId"],
                    configuration["DataProtection:AzureKeyVault:ClientSecret"]);
            }

            // Featured Services
            if (environment.IsDevelopment())
            {
                services.AddSignalR();
            }
            else
            {
                services.AddSignalR().AddStackExchangeRedis(configuration.GetConnectionString("RedisConnection"), options => {
                    options.Configuration.ChannelPrefix = "PipelineSpace";
                });
            }

            // Application
            services.AddScoped <IOrganizationService, OrganizationService>();
            services.AddScoped <IOrganizationQueryService, OrganizationQueryService>();

            services.AddScoped <IOrganizationCMSService, OrganizationCMSService>();
            services.AddScoped <IOrganizationCMSQueryService, OrganizationCMSQueryService>();

            services.AddScoped <IOrganizationCPSService, OrganizationCPSService>();
            services.AddScoped <IOrganizationCPSQueryService, OrganizationCPSQueryService>();

            services.AddScoped <IOrganizationUserService, OrganizationUserService>();
            services.AddScoped <IOrganizationUserQueryService, OrganizationUserQueryService>();

            services.AddScoped <IOrganizationUserInvitationService, OrganizationUserInvitationService>();
            services.AddScoped <IOrganizationUserInvitationQueryService, OrganizationUserInvitationQueryService>();

            services.AddScoped <IProjectService, ProjectService>();
            services.AddScoped <IProjectQueryService, ProjectQueryService>();

            services.AddScoped <IProjectServiceService, ProjectServiceService>();
            services.AddScoped <IProjectServiceQueryService, ProjectServiceQueryService>();

            services.AddScoped <IProjectFeatureService, ProjectFeatureService>();
            services.AddScoped <IProjectFeatureQueryService, ProjectFeatureQueryService>();

            services.AddScoped <IProjectFeatureServiceService, ProjectFeatureServiceService>();
            services.AddScoped <IProjectFeatureServiceQueryService, ProjectFeatureServiceQueryService>();

            services.AddScoped <IProjectEnvironmentService, ProjectEnvironmentService>();
            services.AddScoped <IProjectEnvironmentQueryService, ProjectEnvironmentQueryService>();

            services.AddScoped <IProjectTemplateQueryService, ProjectTemplateQueryService>();
            services.AddScoped <IProjectServiceTemplateQueryService, ProjectServiceTemplateQueryService>();

            services.AddScoped <IProjectActivityQueryService, ProjectActivityQueryService>();
            services.AddScoped <IProjectServiceActivityQueryService, ProjectServiceActivityQueryService>();
            services.AddScoped <IProjectFeatureServiceActivityQueryService, ProjectFeatureServiceActivityQueryService>();

            services.AddScoped <IProjectServiceDeliveryQueryService, ProjectServiceDeliveryQueryService>();
            services.AddScoped <IProjectFeatureServiceDeliveryQueryService, ProjectFeatureServiceDeliveryQueryService>();

            services.AddScoped <IInternalProjectService, InternalProjectService>();
            services.AddScoped <IInternalProjectServiceService, InternalProjectServiceService>();
            services.AddScoped <IInternalProjectFeatureService, InternalProjectFeatureService>();

            services.AddScoped <IInternalProjectActivityService, InternalProjectActivityService>();
            services.AddScoped <IInternalProjectServiceActivityService, InternalProjectServiceActivityService>();
            services.AddScoped <IInternalProjectFeatureServiceActivityService, InternalProjectFeatureServiceActivityService>();

            services.AddScoped <IInternalProjectServiceTemplateService, InternalProjectServiceTemplateService>();

            services.AddScoped <IPublicProjectServiceEventService, PublicProjectServiceEventService>();
            services.AddScoped <IPublicProjectFeatureServiceEventService, PublicProjectFeatureServiceEventService>();

            services.AddScoped <IProjectServiceEventService, ProjectServiceEventService>();
            services.AddScoped <IProjectFeatureServiceEventService, ProjectFeatureServiceEventService>();

            services.AddScoped <IProjectServiceEventQueryService, ProjectServiceEventQueryService>();
            services.AddScoped <IProjectFeatureServiceEventQueryService, ProjectFeatureServiceEventQueryService>();

            services.AddScoped <IProjectServiceEnvironmentService, ProjectServiceEnvironmentService>();
            services.AddScoped <IProjectServiceEnvironmentQueryService, ProjectServiceEnvironmentQueryService>();

            services.AddScoped <IProjectFeatureServiceEnvironmentService, ProjectFeatureServiceEnvironmentService>();
            services.AddScoped <IProjectFeatureServiceEnvironmentQueryService, ProjectFeatureServiceEnvironmentQueryService>();

            services.AddScoped <IProjectServiceCloudQueryService, ProjectServiceCloudQueryService>();
            services.AddScoped <IProjectFeatureServiceCloudQueryService, ProjectFeatureServiceCloudQueryService>();

            services.AddScoped <IProjectUserService, ProjectUserService>();
            services.AddScoped <IProjectUserQueryService, ProjectUserQueryService>();

            services.AddScoped <IProjectUserInvitationService, ProjectUserInvitationService>();
            services.AddScoped <IProjectUserInvitationQueryService, ProjectUserInvitationQueryService>();

            services.AddScoped <IDashboardQueryService, DashboardQueryService>();

            services.AddScoped <ICMSExternalQueryService, CMSExternalQueryService>();

            services.AddScoped <IOrganizationProjectServiceTemplateService, OrganizationProjectServiceTemplateService>();
            services.AddScoped <IOrganizationProjectServiceTemplateQueryService, OrganizationProjectServiceTemplateQueryService>();

            services.AddScoped <IProgrammingLanguageQueryService, ProgrammingLanguageQueryService>();

            services.AddScoped <IProjectCloudCredentialService, ProjectCloudCredentialService>();

            // Domain
            services.AddScoped <IDomainManagerService, DomainManagerService>();

            // Infra - Notification
            if (environment.IsProduction())
            {
                services.AddTransient <IEmailSender, SendGridEmailSender>();
                services.AddTransient <IEmailWorkerService, SendGridEmailWorkerService>();
            }
            else
            {
                services.AddTransient <IEmailSender, PostmarkEmailSender>();
                services.AddTransient <IEmailWorkerService, PostmarkEmailWorkerService>();
            }

            services.AddTransient <ISlugService, DefaultSlugService>();

            // Infra - Identity
            services.AddScoped <IIdentityService, IdentityService>();
            services.AddScoped <IExternalAuthTokenService, AspnetIdentityExternalTokenService>();

            // Infra - Monitor
            services.AddScoped <IDataProtectorService, DataProtectorService>();

            // Infra - Monitor
            services.AddScoped <IActivityMonitorService, ActivityMonitorService>();

            // Infra - Data - Service Agent
            services.AddTransient <IHttpProxyService, HttpProxyService>();

            services.AddTransient <ICMSPipelineService, CMSPipelineServiceAgentRepository>();

            services.AddTransient <CMSVSTSServiceAgentRepository>();
            services.AddTransient <CMSVSTSQueryServiceAgentRepository>();
            services.AddTransient <CMSVSTSCredentialService>();

            services.AddTransient <CMSBitBucketServiceAgentRepository>();
            services.AddTransient <CMSBitBucketQueryServiceAgentRepository>();
            services.AddTransient <CMSBitBucketCredentialService>();

            services.AddTransient <CMSGitHubServiceAgentRepository>();
            services.AddTransient <CMSGitHubQueryServiceAgentRepository>();
            services.AddTransient <CMSGitHubCredentialService>();

            services.AddTransient <CMSGitLabServiceAgentRepository>();
            services.AddTransient <CMSGitLabQueryServiceAgentRepository>();
            services.AddTransient <CMSGitLabCredentialService>();


            services.AddTransient <Func <DomainModels.ConfigurationManagementService, ICMSService> >(serviceProvider => key =>
            {
                switch (key)
                {
                case DomainModels.ConfigurationManagementService.VSTS:
                    return(serviceProvider.GetService <CMSVSTSServiceAgentRepository>());

                case DomainModels.ConfigurationManagementService.Bitbucket:
                    return(serviceProvider.GetService <CMSBitBucketServiceAgentRepository>());

                case DomainModels.ConfigurationManagementService.GitHub:
                    return(serviceProvider.GetService <CMSGitHubServiceAgentRepository>());

                case DomainModels.ConfigurationManagementService.GitLab:
                    return(serviceProvider.GetService <CMSGitLabServiceAgentRepository>());

                default:
                    throw new KeyNotFoundException();
                }
            });

            services.AddTransient <Func <DomainModels.ConfigurationManagementService, ICMSQueryService> >(serviceProvider => key =>
            {
                switch (key)
                {
                case DomainModels.ConfigurationManagementService.VSTS:
                    return(serviceProvider.GetService <CMSVSTSQueryServiceAgentRepository>());

                case DomainModels.ConfigurationManagementService.Bitbucket:
                    return(serviceProvider.GetService <CMSBitBucketQueryServiceAgentRepository>());

                case DomainModels.ConfigurationManagementService.GitHub:
                    return(serviceProvider.GetService <CMSGitHubQueryServiceAgentRepository>());

                case DomainModels.ConfigurationManagementService.GitLab:
                    return(serviceProvider.GetService <CMSGitLabQueryServiceAgentRepository>());

                default:
                    throw new KeyNotFoundException();
                }
            });

            services.AddTransient <Func <DomainModels.ConfigurationManagementService, ICMSCredentialService> >(serviceProvider => key =>
            {
                switch (key)
                {
                case DomainModels.ConfigurationManagementService.VSTS:
                    return(serviceProvider.GetService <CMSVSTSCredentialService>());

                case DomainModels.ConfigurationManagementService.Bitbucket:
                    return(serviceProvider.GetService <CMSBitBucketCredentialService>());

                case DomainModels.ConfigurationManagementService.GitHub:
                    return(serviceProvider.GetService <CMSGitHubCredentialService>());

                case DomainModels.ConfigurationManagementService.GitLab:
                    return(serviceProvider.GetService <CMSGitLabCredentialService>());

                default:
                    throw new KeyNotFoundException();
                }
            });

            services.AddTransient <CPSAWSQueryServiceAgentRepository>();
            services.AddTransient <CPSAzureQueryServiceAgentRepository>();

            services.AddTransient <Func <DomainModels.CloudProviderService, ICPSQueryService> >(serviceProvider => key =>
            {
                switch (key)
                {
                case DomainModels.CloudProviderService.AWS:
                    return(serviceProvider.GetService <CPSAWSQueryServiceAgentRepository>());

                case DomainModels.CloudProviderService.Azure:
                    return(serviceProvider.GetService <CPSAzureQueryServiceAgentRepository>());

                default:
                    throw new KeyNotFoundException();
                }
            });

            services.AddTransient <CPSAWSCredentialService>();
            services.AddTransient <CPSAzureCredentialService>();

            services.AddTransient <Func <DomainModels.CloudProviderService, ICPSCredentialService> >(serviceProvider => key =>
            {
                switch (key)
                {
                case DomainModels.CloudProviderService.AWS:
                    return(serviceProvider.GetService <CPSAWSCredentialService>());

                case DomainModels.CloudProviderService.Azure:
                    return(serviceProvider.GetService <CPSAzureCredentialService>());

                default:
                    throw new KeyNotFoundException();
                }
            });

            //Handler Services
            services.AddTransient <ProjectVSTSHandlerService>();
            services.AddTransient <ProjectBitbucketHandlerService>();
            services.AddTransient <ProjectGitHubHandlerService>();
            services.AddTransient <ProjectGitLabHandlerService>();

            services.AddTransient <Func <DomainModels.ConfigurationManagementService, IProjectHandlerService> >(serviceProvider => key =>
            {
                switch (key)
                {
                case DomainModels.ConfigurationManagementService.VSTS:
                    return(serviceProvider.GetService <ProjectVSTSHandlerService>());

                case DomainModels.ConfigurationManagementService.Bitbucket:
                    return(serviceProvider.GetService <ProjectBitbucketHandlerService>());

                case DomainModels.ConfigurationManagementService.GitHub:
                    return(serviceProvider.GetService <ProjectGitHubHandlerService>());

                case DomainModels.ConfigurationManagementService.GitLab:
                    return(serviceProvider.GetService <ProjectGitLabHandlerService>());

                default:
                    throw new KeyNotFoundException();
                }
            });

            services.AddTransient <ProjectServiceVSTSHandlerService>();
            services.AddTransient <ProjectServiceBitbucketHandlerService>();
            services.AddTransient <ProjectServiceGitHubHandlerService>();

            services.AddTransient <Func <DomainModels.ConfigurationManagementService, IProjectServiceHandlerService> >(serviceProvider => key =>
            {
                switch (key)
                {
                case DomainModels.ConfigurationManagementService.VSTS:
                    return(serviceProvider.GetService <ProjectServiceVSTSHandlerService>());

                case DomainModels.ConfigurationManagementService.Bitbucket:
                    return(serviceProvider.GetService <ProjectServiceBitbucketHandlerService>());

                case DomainModels.ConfigurationManagementService.GitHub:
                    return(serviceProvider.GetService <ProjectServiceGitHubHandlerService>());

                default:
                    throw new KeyNotFoundException();
                }
            });

            services.AddTransient <ProjectFeatureVSTSHandlerService>();
            services.AddTransient <ProjectFeatureBitbucketHandlerService>();
            services.AddTransient <ProjectFeatureGitHubHandlerService>();

            services.AddTransient <Func <DomainModels.ConfigurationManagementService, IProjectFeatureHandlerService> >(serviceProvider => key =>
            {
                switch (key)
                {
                case DomainModels.ConfigurationManagementService.VSTS:
                    return(serviceProvider.GetService <ProjectFeatureVSTSHandlerService>());

                case DomainModels.ConfigurationManagementService.Bitbucket:
                    return(serviceProvider.GetService <ProjectFeatureBitbucketHandlerService>());

                case DomainModels.ConfigurationManagementService.GitHub:
                    return(serviceProvider.GetService <ProjectFeatureGitHubHandlerService>());

                default:
                    throw new KeyNotFoundException();
                }
            });

            services.AddTransient <CPSAWSService>();
            services.AddTransient <CPSAzureService>();

            services.AddTransient <Func <DomainModels.CloudProviderService, ICPSService> >(serviceProvider => key =>
            {
                switch (key)
                {
                case DomainModels.CloudProviderService.AWS:
                    return(serviceProvider.GetService <CPSAWSService>());

                case DomainModels.CloudProviderService.Azure:
                    return(serviceProvider.GetService <CPSAzureService>());

                default:
                    throw new KeyNotFoundException();
                }
            });

            services.AddTransient <VSTSTokenProviderService>();
            services.AddTransient <GitHubTokenProviderService>();
            services.AddTransient <BitbucketTokenProviderService>();

            services.AddTransient <Func <string, ITokenProviderService> >(serviceProvider => key =>
            {
                switch (key.ToLower())
                {
                case "vsts":
                    return(serviceProvider.GetService <VSTSTokenProviderService>());

                case "github":
                    return(serviceProvider.GetService <GitHubTokenProviderService>());

                case "bitbucket":
                    return(serviceProvider.GetService <BitbucketTokenProviderService>());

                default:
                    throw new KeyNotFoundException();
                }
            });

            // Infra - Data - SqlServer
            services.AddScoped <IUserRepository, UserSqlServerRepository>();
            services.AddScoped <IOrganizationRepository, OrganizationSqlServerRepository>();
            services.AddScoped <IOrganizationCMSRepository, OrganizationCMSSqlServerRepository>();
            services.AddScoped <IOrganizationCPSRepository, OrganizationCPSSqlServerRepository>();
            services.AddScoped <IOrganizationUserInvitationRepository, OrganizationUserInvitationSqlServerRepository>();
            services.AddScoped <IProjectRepository, ProjectSqlServerRepository>();
            services.AddScoped <IProjectServiceRepository, ProjectServiceSqlServerRepository>();
            services.AddScoped <IProjectFeatureRepository, ProjectFeatureSqlServerRepository>();
            services.AddScoped <IProjectTemplateRepository, ProjectTemplateSqlServerRepository>();
            services.AddScoped <IProjectServiceTemplateRepository, ProjectServiceTemplateSqlServerRepository>();

            services.AddScoped <IProjectActivityRepository, ProjectActivitySqlServerRepository>();
            services.AddScoped <IProjectServiceActivityRepository, ProjectServiceActivitySqlServerRepository>();
            services.AddScoped <IProjectFeatureServiceActivityRepository, ProjectFeatureServiceActivitySqlServerRepository>();
            services.AddScoped <IProjectUserInvitationRepository, ProjectUserInvitationSqlServerRepository>();

            services.AddScoped <IProgrammingLanguageRepository, ProgrammingLanguageSqlServerRepository>();

            services.AddScoped(x => new PipelineSpaceDbContextFactory().Create(configuration.GetConnectionString("DefaultConnection")));
            services.AddDbContext <PipelineSpaceDbContext>(options =>
                                                           options.UseLazyLoadingProxies()
                                                           .UseSqlServer(configuration.GetConnectionString("DefaultConnection"),
                                                                         sqlServerOptionsAction: sqlOptions =>
            {
                sqlOptions.EnableRetryOnFailure(
                    maxRetryCount: 10,
                    maxRetryDelay: TimeSpan.FromSeconds(30),
                    errorNumbersToAdd: null);
            })
                                                           );

            services.AddIdentity <DomainModels.User, IdentityRole>(o =>
            {
                // User settings
                o.User.RequireUniqueEmail = true;

                // Sign In settings
                //o.SignIn.RequireConfirmedEmail = true;
                //o.SignIn.RequireConfirmedPhoneNumber = true;

                // Password settings
                o.Password.RequireDigit           = true;
                o.Password.RequireLowercase       = true;
                o.Password.RequireUppercase       = true;
                o.Password.RequireNonAlphanumeric = true;
                o.Password.RequiredLength         = 8;
            })
            .AddEntityFrameworkStores <PipelineSpaceDbContext>()
            .AddDefaultTokenProviders();

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddBitbucket(options =>
            {
                options.ClientId     = configuration["Authentication:Bitbucket:ClientId"];
                options.ClientSecret = configuration["Authentication:Bitbucket:ClientSecret"];

                var scopes = configuration["Authentication:Bitbucket:Scopes"].Split(',');

                foreach (var item in scopes)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        options.Scope.Add(item);
                    }
                }

                options.SaveTokens = true;
            })
            .AddGitHub(options =>
            {
                options.ClientId     = configuration["Authentication:GitHub:ClientId"];
                options.ClientSecret = configuration["Authentication:GitHub:ClientSecret"];
                var scopes           = configuration["Authentication:GitHub:Scopes"].Split(',');

                foreach (var item in scopes)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        options.Scope.Add(item);
                    }
                }

                options.SaveTokens = true;
            })
            .AddVisualStudio("VSTS", "Visual Studio Team Services", options =>
            {
                options.ClientId              = configuration["Authentication:VisualStudio:ClientId"];
                options.ClientSecret          = configuration["Authentication:VisualStudio:ClientSecret"];
                options.CallbackPath          = new PathString("/signin-vsts");
                options.TokenEndpoint         = "https://app.vssps.visualstudio.com/oauth2/token";
                options.AuthorizationEndpoint = "https://app.vssps.visualstudio.com/oauth2/authorize";

                var scopes = configuration["Authentication:VisualStudio:Scopes"].Split(',');

                options.Scope.Clear();

                foreach (var item in scopes)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        options.Scope.Add(item);
                    }
                }

                options.SaveTokens = true;
            });

            var migrationsAssembly = typeof(PipelineSpaceDbContext).GetTypeInfo().Assembly.GetName().Name;

            var identityServerBuilder = services.AddIdentityServer()
                                        .AddAspNetIdentity <DomainModels.User>()
                                        .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"),
                                                                  sqlServerOptionsAction: sqlOptions =>
                {
                    sqlOptions.MigrationsAssembly(migrationsAssembly);
                    sqlOptions.EnableRetryOnFailure(
                        maxRetryCount: 10,
                        maxRetryDelay: TimeSpan.FromSeconds(30),
                        errorNumbersToAdd: null);
                });
            })
                                        .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"),
                                                                  sqlServerOptionsAction: sqlOptions =>
                {
                    sqlOptions.MigrationsAssembly(migrationsAssembly);
                    sqlOptions.EnableRetryOnFailure(
                        maxRetryCount: 10,
                        maxRetryDelay: TimeSpan.FromSeconds(30),
                        errorNumbersToAdd: null);
                });
                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup   = true;
                options.TokenCleanupInterval = 30;
            });

            if (environment.IsDevelopment())
            {
                identityServerBuilder.AddDeveloperSigningCredential();
            }
            else
            {
                var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(async(authority, resource, scope) =>
                {
                    var authContext = new AuthenticationContext(authority);
                    ClientCredential clientCreds = new ClientCredential(configuration["DataProtection:AzureKeyVault:ClientId"], configuration["DataProtection:AzureKeyVault:ClientSecret"]);

                    AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCreds);

                    if (result == null)
                    {
                        throw new InvalidOperationException("Failed to obtain the JWT token");
                    }

                    return(result.AccessToken);
                }));

                var pfxSecret   = keyVaultClient.GetSecretAsync(configuration["DataProtection:AzureKeyVault:SecretIdentifier"]).Result;
                var pfxBytes    = Convert.FromBase64String(pfxSecret.Value);
                var certificate = new X509Certificate2(pfxBytes);

                identityServerBuilder.AddSigningCredential(certificate);
            }

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            // Infra - Messaging
            if (environment.IsDevelopment())
            {
                services.AddTransient <IEventBusService, InMemoryEventBusService>();
            }
            else
            {
                services.AddTransient <IEventBusService, AzureEventBusService>();
            }

            //Polly Policies
            IPolicyRegistry <string> registry = services.AddPolicyRegistry();

            IAsyncPolicy <HttpResponseMessage> httpRetryPolicy =
                Policy.HandleResult <HttpResponseMessage>(r => !r.IsSuccessStatusCode)
                .RetryAsync(3);

            registry.Add("SimpleHttpRetryPolicy", httpRetryPolicy);

            Random jitterer = new Random();

            IAsyncPolicy <HttpResponseMessage> httWaitAndpRetryPolicy =
                Policy.HandleResult <HttpResponseMessage>(r => !r.IsSuccessStatusCode)
                .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))
                                   + TimeSpan.FromMilliseconds(jitterer.Next(0, 100)));

            registry.Add("SimpleWaitAndRetryPolicy", httWaitAndpRetryPolicy);

            IAsyncPolicy <HttpResponseMessage> noOpPolicy = Policy.NoOpAsync()
                                                            .AsAsyncPolicy <HttpResponseMessage>();

            registry.Add("NoOpPolicy", noOpPolicy);

            services.AddHttpClient("RemoteServerFromService", client =>
            {
                client.DefaultRequestHeaders.Add("Accept", "application/json");
            })
            .AddPolicyHandlerFromRegistry((policyRegistry, httpRequestMessage) =>
            {
                if (httpRequestMessage.Method == HttpMethod.Get)
                {
                    return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("SimpleHttpRetryPolicy"));
                }
                else if (httpRequestMessage.Method == HttpMethod.Post)
                {
                    return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("NoOpPolicy"));
                }
                else
                {
                    return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("SimpleWaitAndRetryPolicy"));
                }
            })
            .AddPolicyHandler((httpRequestMessage) => {
                return(HttpPolicyExtensions.HandleTransientHttpError().CircuitBreakerAsync(5, TimeSpan.FromSeconds(30)));
            });

            services.AddHttpClient("RemoteServerFromWorker", client =>
            {
                client.DefaultRequestHeaders.Add("Accept", "application/json");
            })
            .AddPolicyHandlerFromRegistry((policyRegistry, httpRequestMessage) =>
            {
                if (httpRequestMessage.Method == HttpMethod.Get)
                {
                    return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("SimpleHttpRetryPolicy"));
                }
                else if (httpRequestMessage.Method == HttpMethod.Post)
                {
                    return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("NoOpPolicy"));
                }
                else
                {
                    return(policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >("SimpleWaitAndRetryPolicy"));
                }
            })
            .AddPolicyHandler((httpRequestMessage) => {
                return(HttpPolicyExtensions.HandleTransientHttpError().CircuitBreakerAsync(5, TimeSpan.FromSeconds(30)));
            });

            services.AddTransient <Worker.Handlers.Services.Interfaces.IPipelineSpaceManagerService, PipelineSpaceManagerService>();
            services.AddTransient <IHttpClientWrapperService, HttpClientWrapperService>();
            services.AddTransient <IRealtimeService, RealtimeService>();
            services.AddTransient <IUserIdProvider, NameUserIdProvider>();
            services.AddTransient <ITemplateService, PipelineSpaceTemplateRepository>();

            services.AddTransient <IEventHandler <ProjectCreatedEvent>, ProjectCreatedHandler>();
            services.AddTransient <IEventHandler <ProjectImportedEvent>, ProjectImportedHandler>();
            services.AddTransient <IEventHandler <ProjectServiceCreatedEvent>, ProjectServiceCreatedHandler>();
            services.AddTransient <IEventHandler <ProjectServiceImportedEvent>, ProjectServiceImportedHandler>();
            services.AddTransient <IEventHandler <ProjectFeatureCreatedEvent>, ProjectFeatureCreatedHandler>();
            services.AddTransient <IEventHandler <ProjectFeatureServiceCreatedEvent>, ProjectFeatureServiceCreatedHandler>();

            services.AddTransient <IEventHandler <ProjectServiceBuildQueuedEvent>, ProjectServiceBuildQueuedHandler>();
            services.AddTransient <IEventHandler <ProjectFeatureServiceBuildQueuedEvent>, ProjectFeatureServiceBuildQueuedHandler>();

            services.AddTransient <IEventHandler <OrganizationDeletedEvent>, OrganizationDeletedHandler>();
            services.AddTransient <IEventHandler <ProjectDeletedEvent>, ProjectDeletedHandler>();
            services.AddTransient <IEventHandler <ProjectServiceDeletedEvent>, ProjectServiceDeletedHandler>();
            services.AddTransient <IEventHandler <ProjectFeatureDeletedEvent>, ProjectFeatureDeletedHandler>();
            services.AddTransient <IEventHandler <ProjectFeatureServiceDeletedEvent>, ProjectFeatureServiceDeletedHandler>();
            services.AddTransient <IEventHandler <ProjectFeatureCompletedEvent>, ProjectFeatureCompletedHandler>();

            services.AddTransient <IEventHandler <ProjectEnvironmentActivatedEvent>, ProjectEnvironmentActivatedHandler>();
            services.AddTransient <IEventHandler <ProjectEnvironmentCreatedEvent>, ProjectEnvironmentCreatedHandler>();
            services.AddTransient <IEventHandler <ProjectEnvironmentDeletedEvent>, ProjectEnvironmentDeletedHandler>();
            services.AddTransient <IEventHandler <ProjectEnvironmentInactivatedEvent>, ProjectEnvironmentInactivatedHandler>();

            services.AddTransient <IEventHandler <ProjectFeatureEnvironmentCreatedEvent>, ProjectFeatureEnvironmentCreatedHandler>();

            services.AddTransient <IEventHandler <ProjectServiceTemplateCreatedEvent>, ProjectServiceTemplateCreatedHandler>();
        }
Пример #14
0
 public void Add(IAsyncPolicy <IContinuation> policy)
 {
     _policies.Add(policy);
 }
Пример #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("AllowFromAll",
                                  builder => builder
                                  .WithMethods("GET", "POST", "PUT")
                                  .AllowAnyOrigin()
                                  .AllowAnyHeader());
            });
            services.AddControllers();

            //#if (AddHealthCheck)
            // Register health checks to be enabled in api
            services.AddHealthChecks()
            .AddCheck("self", () => HealthCheckResult.Healthy());
            //#endif

            //#if (AddSwagger)
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "CMAService API", Version = "v1"
                });
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });
            //#endif

            services.AddScoped <IBusinessAccess, BusinessAccess>();
            //#if (!AddSql && !AddMongo)
            services.AddScoped <IDataAccess, DataAccess>();
            //#endif
            // services.AddScoped<IDataAccess, CouchDataAccess>();
            //#if(AddSql)
            //services.AddScoped<IDataAccess, SqlDataAccess>();

            services.AddDbContext <AuthorContext>(options =>
            {
                options.UseSqlServer(
                    Configuration.GetConnectionString("SqlDatabase"));
            });

            //#endif

            //#if(AddMongo)
            // requires using Microsoft.Extensions.Options
            services.Configure <MongoDbSettings>(
                Configuration.GetSection(nameof(MongoDbSettings)));

            services.AddSingleton <IMongoDbSettings>(sp =>
                                                     sp.GetRequiredService <IOptions <MongoDbSettings> >().Value);

            //services.AddScoped<IDataAccess, MongoDataAccess>();


            //#endif
            //#if (AddPolly)
            IAsyncPolicy <HttpResponseMessage> httpWaitAndRetryPolicy = GetWaitAndRetryPolicy();
            IAsyncPolicy <HttpResponseMessage> circuitBreakerPolicy   = GetCircuitBreakerPolicy();
            IAsyncPolicy <HttpResponseMessage> fallbackPolicy         = GetFallbackPolicy();
            IAsyncPolicy <HttpResponseMessage> httpRetryPolicy        = GetRetryPolicy();
            IAsyncPolicy <HttpResponseMessage> allPoliciesWrapped     = Policy.WrapAsync(fallbackPolicy, httpWaitAndRetryPolicy, circuitBreakerPolicy);

            services.AddHttpClient("WeatherForecastController", client =>
            {
                client.BaseAddress = new Uri("https://localhost:44358/weatherforecast/GetErrorPollyTest?id=5");
                client.DefaultRequestHeaders.Add("Accept", "application/json");
            }).AddPolicyHandler(httpRetryPolicy);

            //#endif
            //#if(AddKafka)
            var producerConfig = new ProducerConfig();
            var consumerConfig = new ConsumerConfig();

            Configuration.Bind("producer", producerConfig);
            Configuration.Bind("consumer", consumerConfig);

            services.AddSingleton <ProducerConfig>(producerConfig);
            services.AddSingleton <ConsumerConfig>(consumerConfig);
            //#endif

            //#if(AddJager)
            services.AddSingleton <ITracer>(serviceProvider =>
            {
                var loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>();
                Environment.SetEnvironmentVariable(Jaeger.Configuration.JaegerServiceName, Configuration["JagerConnection:servicename"]);
                Environment.SetEnvironmentVariable(Jaeger.Configuration.JaegerSamplerType, Configuration["JagerConnection:sampletype"]);
                Environment.SetEnvironmentVariable(Jaeger.Configuration.JaegerReporterLogSpans, Configuration["JagerConnection:reportlogspan"]);
                Environment.SetEnvironmentVariable(Jaeger.Configuration.JaegerSamplerParam, Configuration["JagerConnection:samplerparam"]);
                Environment.SetEnvironmentVariable(Jaeger.Configuration.JaegerEndpoint, Configuration["JagerConnection:endpoint"]);
                // This will log to a default localhost installation of Jaeger.
                var tracer = Jaeger.Configuration.FromEnv(loggerFactory).GetTracer();

                // Allows code that can't use DI to also access the tracer.
                GlobalTracer.Register(tracer);

                return(tracer);
            });

            services.AddOpenTracing();
            //#endif
            //#if(AddRedis)
            services.AddDistributedRedisCache(option =>
            {
                option.Configuration = Configuration["RedisConnection:hostname"];
                option.InstanceName  = Configuration["RedisConnection:instancename"];
            });
            //#endif

            //#if(AddCouch)
            var constring = Configuration["Couchbase:Server"];

            services.AddSingleton <CouchClient>(new CouchClient(constring));
            //#endif
        }
Пример #16
0
 public RestClientFactory <TResult> SetAsyncPolicy(IAsyncPolicy <TResult> asyncPolicyGeneric)
 {
     _pollyRetAsyncPolicyGeneric = asyncPolicyGeneric;
     return(InstanceRestClient);
 }
 public static Policy GenerateRestRepositoryPolicy(IAsyncPolicy chainedPolicy)
 {
     return(GenerateRestRepositoryPolicy(new[] { chainedPolicy }));
 }
Пример #18
0
 public ValidarCursosGsaUseCase(IMediator mediator, IReadOnlyPolicyRegistry <string> registry)
 {
     this.mediator = mediator;
     this.policy   = registry.Get <IAsyncPolicy>(PoliticaPolly.PolicyCargaGsa);
 }
Пример #19
0
 /// <summary>Initializes a new instance of the <see cref="HttpClientRetryPolicyHandler"/> class.</summary>
 public HttpClientRetryPolicyHandler(IAsyncPolicy <HttpResponseMessage> retryPolicy)
 {
     _retryPolicy = retryPolicy ?? throw new ArgumentNullException(nameof(retryPolicy));
 }
Пример #20
0
 public PollyEventHandler(IEventHandler inner, IAsyncPolicy retryPolicy)
 {
     _inner         = inner;
     _retryPolicy   = retryPolicy;
     DiagnosticName = _inner.DiagnosticName;
 }
 public ResilienceService()
 {
     this.wrapStrategyAsync = Policy.WrapAsync(this.GetRetryAsync(), this.GetCircuitBreakerAsync());
 }
 public PollyPolicyDelegatingHandler(IAsyncPolicy <HttpResponseMessage> policy) =>
 this.policy = policy ?? throw new ArgumentNullException(nameof(policy));
 public PublicarFilaAeCommandHandler(IReadOnlyPolicyRegistry <string> registry, ConnectionFactory connectionFactory)
 {
     this.connectionFactory = connectionFactory ?? throw new ArgumentNullException(nameof(connectionFactory));
     this.policy            = registry.Get <IAsyncPolicy>(PoliticaPolly.PublicaFila);
 }
 public ObterAtividadesDoCursoGoogleQueryHandler(IMediator mediator, IReadOnlyPolicyRegistry <string> registry)
     : base()
 {
     this.mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
     this.policy   = registry.Get <IAsyncPolicy>(PoliticaPolly.PolicyCargaGsa);
 }
Пример #25
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="registry"></param>
 /// <param name="distributedCache"></param>
 public PolicyDistributedCacheDecorator(IReadOnlyPolicyRegistry <string> registry, IDistributedCache distributedCache)
 {
     _distributedCache = distributedCache;
     _syncPolicy       = registry.Get <ISyncPolicy>(PollyPolicies.SyncPolicy);
     _asyncPolicy      = registry.Get <IAsyncPolicy>(PollyPolicies.AsyncPolicy);
 }
Пример #26
0
        public IAsyncPolicy <T> Polly(PolicyBuilder <T> policy, ILogger <CircuitBreakerOptions <T> > log)
        {
            return(_policy = _policy ?? PolicyOrNoOP(FailPolicy == "fail" ? LogAndFail() : LogOnly()));


            IAsyncPolicy <T> LogOnly()
            {
                return(CircuitPolicy()
                       .WrapAsync(RerunFallback()));
            }

            IAsyncPolicy <T> LogAndFail()
            {
                return
                    (CircuitPolicy());
            }

            IAsyncPolicy RerunFallback()
            {
                return(Policy
                       .Handle <BrokenCircuitException>()
                       .RetryAsync());
            }

            IAsyncPolicy <T> CircuitPolicy()
            {
                return(policy
                       .AdvancedCircuitBreakerAsync(
                           failureThreshold: FailureThreshold,
                           samplingDuration: TimeSpan.FromMilliseconds(SamplingDuration),
                           minimumThroughput: MinimumThroughput,
                           durationOfBreak: TimeSpan.FromMilliseconds(DurationOfBreak),
                           onBreak: logOnBreak,
                           onReset: logOnReset,
                           onHalfOpen: logOnHalfOpen
                           ));
            }

            void logOnHalfOpen()
            {
                log.Log(LogLevel.Warning, 0, state: new BrokenCircuitStatus()
                {
                }, null, (status, exception) => "Circuit breaker on half open");
            }

            void logOnReset(Context context)
            {
                log.Log(LogLevel.Warning, 0, state: new BrokenCircuitStatus()
                {
                    OperationKey  = context.OperationKey,
                    PolicyKey     = context.PolicyKey,
                    CorrelationId = context.CorrelationId,
                }, null, (status, exception) => "Circuit breaker on reset");
            }

            void logOnBreak(DelegateResult <T> result, CircuitState circuitState, TimeSpan timeSpan,
                            Context context)
            {
                log.Log(LogLevel.Error, 0, state: new BrokenCircuitStatus()
                {
                    OperationKey  = context.OperationKey,
                    PolicyKey     = context.PolicyKey,
                    CorrelationId = context.CorrelationId,
                    TimeSpan      = timeSpan,
                    CircuitState  = circuitState
                }, result.Exception, (status, exception) => "Circuit breaker is open");
            }
        }
 public PollyMiddleware(IAsyncPolicy policy)
 {
     _policy = policy;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="NamedAsyncPolicy"/> class.
 /// </summary>
 /// <param name="name">Name of the policy.</param>
 /// <param name="delegatedPolicy"><see cref="IAsyncPolicy"/> to delegate to.</param>
 public NamedAsyncPolicy(string name, IAsyncPolicy delegatedPolicy)
     : base(delegatedPolicy)
 {
     Name = name;
 }
Пример #29
0
 public AtualizarAlunoGoogleCommandHandler(IMediator mediator, IReadOnlyPolicyRegistry <string> registry, VariaveisGlobaisOptions variaveisGlobaisOptions)
     : base(variaveisGlobaisOptions)
 {
     this.mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
     this.policy   = registry.Get <IAsyncPolicy>(PoliticaPolly.PolicyGoogleSync);
 }
Пример #30
0
 public PerfLogRepository(HippologamusContext context, IAsyncPolicy retryPolicy)
     : base(context, retryPolicy)
 {
 }