Ejemplo n.º 1
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     builder.Services.AddSingleton <IConfigCacheClient>((s) => {
         return(new ConfigCacheClient());
     });
 }
Ejemplo n.º 2
0
 /// <summary>
 /// 共通のDI設定を行う。
 /// </summary>
 /// <param name="builder">ビルダー</param>
 /// <returns>IFunctionsHostBuilder</returns>
 public static IFunctionsHostBuilder AddUtility(IFunctionsHostBuilder builder)
 {
     AddUtility(builder.Services);
     return(builder);
 }
Ejemplo n.º 3
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     builder.Services.AddScoped <IMediaService, MediaService>();
 }
Ejemplo n.º 4
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     // Handle DIs if required
 }
Ejemplo n.º 5
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
 }
Ejemplo n.º 6
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     builder.Services.AddLogging();
 }
Ejemplo n.º 7
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            // Add Options
            var context = builder.GetContext();

            var section = context.Configuration.GetSection("Acmebot");

            builder.Services.AddOptions <AcmebotOptions>()
            .Bind(section.Exists() ? section : context.Configuration.GetSection("LetsEncrypt"))
            .ValidateDataAnnotations();

            // Add Services
            builder.Services.Replace(ServiceDescriptor.Transient(typeof(IOptionsFactory <>), typeof(OptionsFactory <>)));

            builder.Services.AddHttpClient();
            builder.Services.AddHttpClient("InSecure")
            .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
            });

            builder.Services.AddSingleton <ITelemetryInitializer, ApplicationVersionInitializer <Startup> >();

            builder.Services.AddSingleton(new LookupClient(new LookupClientOptions(NameServer.GooglePublicDns, NameServer.GooglePublicDns2)
            {
                UseCache            = false,
                UseRandomNameServer = true
            }));

            builder.Services.AddSingleton <ITokenProvider, AppAuthenticationTokenProvider>();

            builder.Services.AddSingleton(provider =>
            {
                var options = provider.GetRequiredService <IOptions <AcmebotOptions> >();

                return(AzureEnvironment.Get(options.Value.Environment));
            });

            builder.Services.AddSingleton(provider =>
            {
                var options     = provider.GetRequiredService <IOptions <AcmebotOptions> >();
                var environment = provider.GetRequiredService <AzureEnvironment>();

                return(new WebSiteManagementClient(new Uri(environment.ResourceManager), new TokenCredentials(provider.GetRequiredService <ITokenProvider>()))
                {
                    SubscriptionId = options.Value.SubscriptionId
                });
            });

            builder.Services.AddSingleton(provider =>
            {
                var options     = provider.GetRequiredService <IOptions <AcmebotOptions> >();
                var environment = provider.GetRequiredService <AzureEnvironment>();

                return(new DnsManagementClient(new Uri(environment.ResourceManager), new TokenCredentials(provider.GetRequiredService <ITokenProvider>()))
                {
                    SubscriptionId = options.Value.SubscriptionId
                });
            });

            builder.Services.AddSingleton(provider =>
            {
                var options     = provider.GetRequiredService <IOptions <AcmebotOptions> >();
                var environment = provider.GetRequiredService <AzureEnvironment>();

                return(new ResourceManagementClient(new Uri(environment.ResourceManager), new TokenCredentials(provider.GetRequiredService <ITokenProvider>()))
                {
                    SubscriptionId = options.Value.SubscriptionId
                });
            });

            builder.Services.AddSingleton <AcmeProtocolClientFactory>();
            builder.Services.AddSingleton <KuduClientFactory>();

            builder.Services.AddSingleton <WebhookInvoker>();
            builder.Services.AddSingleton <ILifeCycleNotificationHelper, WebhookLifeCycleNotification>();
        }
Ejemplo n.º 8
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     builder.Services.AddHttpClient();
 }
Ejemplo n.º 9
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     builder.Services.AddSingleton <HttpClient>(new HttpClient());
 }
Ejemplo n.º 10
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     ConfigureServices(builder.Services).BuildServiceProvider(true);
 }
 public override void Configure(IFunctionsHostBuilder builder)
 {
     RegisterWebJobServices(builder.Services);
     RegisterServices(builder.Services);
 }
Ejemplo n.º 12
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     RegisterComponents(builder.Services);
 }
Ejemplo n.º 13
0
 private static void SetExecutionContextOptions(IFunctionsHostBuilder builder)
 {
     builder.Services.Configure <ExecutionContextOptions>(o => o.AppDirectory = Directory.GetCurrentDirectory());
 }
Ejemplo n.º 14
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     SetExecutionContextOptions(builder);
     base.Configure(builder);
 }
Ejemplo n.º 15
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var connectionString = Environment.GetEnvironmentVariable("APP_CONFIG_CONNECTION");
            var settings         = new AppSettings();
            var config           = new ConfigurationBuilder()
                                   .AddEnvironmentVariables()
                                   .AddAzureAppConfiguration(connectionString)
                                   .Build();

            config.Bind(settings);

            var cosmosConfig = new CosmosConfig(
                settings.CosmosSettings.DatabaseName,
                settings.CosmosSettings.EndpointUri,
                settings.CosmosSettings.PrimaryKey,
                settings.CosmosSettings.RequestTimeoutInSeconds
                );

            var cosmosContainers = new List <ContainerInfo>()
            {
                new ContainerInfo()
                {
                    Name         = "salesorderdetail",
                    PartitionKey = "/PartitionKey"
                },
                new ContainerInfo()
                {
                    Name         = "purchaseorderdetail",
                    PartitionKey = "/PartitionKey"
                },
                new ContainerInfo()
                {
                    Name         = "lineitemdetail",
                    PartitionKey = "/PartitionKey"
                },
                new ContainerInfo()
                {
                    Name         = "rmas",
                    PartitionKey = "/PartitionKey"
                },
                new ContainerInfo()
                {
                    Name         = "shipmentdetail",
                    PartitionKey = "/PartitionKey"
                },
                new ContainerInfo()
                {
                    Name         = "productdetail",
                    PartitionKey = "/PartitionKey"
                }
            };

            // https://github.com/Polly-Contrib/Polly.Contrib.WaitAndRetry#wait-and-retry-with-jittered-back-off
            var delay  = Backoff.DecorrelatedJitterBackoffV2(medianFirstRetryDelay: TimeSpan.FromSeconds(30), retryCount: 3);
            var policy = HttpPolicyExtensions
                         .HandleTransientHttpError()
                         .OrResult(response => response.StatusCode == HttpStatusCode.TooManyRequests)
                         .WaitAndRetryAsync(delay);

            var flurlClientFactory = new PerBaseUrlFlurlClientFactory();

            FlurlHttp.Configure(settings => settings.HttpClientFactory = new PollyFactory(policy));

            builder.Services
            .InjectOrderCloud <IOrderCloudClient>(new OrderCloudClientConfig()
            {
                ApiUrl       = settings.OrderCloudSettings.ApiUrl,
                AuthUrl      = settings.OrderCloudSettings.ApiUrl,
                ClientId     = settings.OrderCloudSettings.MiddlewareClientID,
                ClientSecret = settings.OrderCloudSettings.MiddlewareClientSecret,
                Roles        = new[]
                {
                    ApiRole.FullAccess
                }
            })
            .AddCosmosDb(settings.CosmosSettings.EndpointUri, settings.CosmosSettings.PrimaryKey, settings.CosmosSettings.DatabaseName, cosmosContainers)
            .AddSingleton <IFlurlClientFactory, PerBaseUrlFlurlClientFactory>()
            .AddSingleton <IOrderCloudIntegrationsCardConnectService>(x => new OrderCloudIntegrationsCardConnectService(settings.CardConnectSettings, settings.EnvironmentSettings.Environment.ToString(), flurlClientFactory))
            .Inject <IHSCatalogCommand>()
            .Inject <IHSBuyerLocationCommand>()
            .AddSingleton <PaymentCaptureJob>()
            .AddSingleton <SendRecentOrdersJob>()
            .AddSingleton <ReceiveRecentSalesOrdersJob>()
            .AddSingleton <ReceiveProductDetailsJob>()
            .AddSingleton <ReceiveRecentPurchaseOrdersJob>()
            .AddSingleton <ReceiveRecentLineItemsJob>()
            .AddSingleton <ReceiveRecentOrdersAndShipmentsJob>()
            .AddSingleton(x => new ZohoClientConfig
            {
                ApiUrl         = "https://books.zoho.com/api/v3",
                AccessToken    = settings.ZohoSettings.AccessToken,
                ClientId       = settings.ZohoSettings.ClientId,
                ClientSecret   = settings.ZohoSettings.ClientSecret,
                OrganizationID = settings.ZohoSettings.OrgID
            })
            .Inject <IZohoClient>()
            .Inject <IZohoCommand>()
            .AddSingleton <ISendGridClient>(x => new SendGridClient(settings.SendgridSettings.ApiKey))
            .Inject <ISendgridService>()
            .Inject <ISalesOrderDetailDataRepo>()
            .Inject <IPurchaseOrderDetailDataRepo>()
            .Inject <ILineItemDetailDataRepo>()
            .Inject <IOrdersAndShipmentsDataRepo>()
            .AddSingleton(settings)
            .AddMvcCore().AddNewtonsoftJson(o =>
            {
                o.SerializerSettings.ContractResolver = new DefaultContractResolver();
                o.SerializerSettings.Converters.Add(new StringEnumConverter());
                o.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            })
            .Services.Replace(ServiceDescriptor.Singleton(typeof(IConfiguration), config));
        }
Ejemplo n.º 16
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     builder.Services.AddScoped <IEmployeeService, EmployeeService>();
 }
Ejemplo n.º 17
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     builder.Services.AddSingleton <PromotionsRepository>();
 }
Ejemplo n.º 18
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     builder.Services.AddSingleton <ISomeService, SomeService>();
 }
 private static void Configure(IFunctionsHostBuilder builder)
 {
     // register other services here
 }
Ejemplo n.º 20
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var sp = builder.Services.BuildServiceProvider();

            var configuration = sp.GetService <IConfiguration>();

            var nLogConfiguration = new NLogConfiguration();

            var tempConfig = new ConfigurationBuilder()
                             .SetBasePath(Directory.GetCurrentDirectory())
                             .AddEnvironmentVariables()
                             .AddJsonFile("local.settings.json", true).Build();

            builder.Services.AddLogging((options) =>
            {
                options.SetMinimumLevel(LogLevel.Trace);
                options.AddNLog(new NLogProviderOptions
                {
                    CaptureMessageTemplates  = true,
                    CaptureMessageProperties = true
                });
                options.AddConsole();

                nLogConfiguration.ConfigureNLog(tempConfig);
            });

            var config = new ConfigurationBuilder()
                         .AddConfiguration(configuration)
                         .AddEnvironmentVariables()
                         .AddAzureTableStorage(options =>
            {
                options.ConfigurationKeys = new[] { tempConfig.GetValue <string>("AppName") };
                options.EnvironmentNameEnvironmentVariableName         = "EnvironmentName";
                options.StorageConnectionStringEnvironmentVariableName = "ConfigurationStorageConnectionString";
                options.PreFixConfigurationKeys = false;
            })
                         .Build();

            builder.Services.AddOptions();
            builder.Services.Configure <ConnectionStrings>(config.GetSection("ConnectionStrings"));

            builder.Services.AddMediatR(typeof(ContentPublishHandler));

            builder.Services.Configure <ContentfulOptions>(config.GetSection("ContentfulOptions"));
            builder.Services.AddTransient <ConnectionMultiplexer>(services =>
            {
                var connectionStrings = services.GetService <IOptions <ConnectionStrings> >().Value;
                return(ConnectionMultiplexer.Connect($"{connectionStrings.RedisConnectionString},{connectionStrings.ContentCacheDatabase},allowAdmin=true"));
            });
            builder.Services.AddTransient <IDatabase>(client =>
            {
                return(client.GetService <ConnectionMultiplexer>().GetDatabase());
            });
            builder.Services.AddTransient <ContentfulClient>(services => {
                var contentfulOptions = services.GetService <IOptions <ContentfulOptions> >().Value;
                return(new ContentfulClient(new System.Net.Http.HttpClient(), contentfulOptions.DeliveryApiKey, contentfulOptions.PreviewApiKey, contentfulOptions.SpaceId, contentfulOptions.UsePreviewApi));
            });
            builder.Services.AddTransient <IContentService, ContentService>();
            builder.Services.AddTransient <ICacheService, CacheService>();
            builder.Services.AddTransient <IArticleMapping, ArticleMapping>();
        }
Ejemplo n.º 21
0
    public override void Configure(IFunctionsHostBuilder builder)
    {
        if (builder is null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        var configuration = GetConfiguration(builder.Services);

        builder.Services
        .AddSingleton(configuration)
        .AddTeamCloudOptions(Assembly.GetExecutingAssembly())
        .AddTeamCloudOptionsShared()
        .AddTeamCloudGraph()
        .AddTeamCloudAzure(configuration =>
        {
            configuration
            .AddResources()
            .AddDeployment()
            .SetDeploymentArtifactsProvider <AzureStorageArtifactsProvider>();
        })
        .AddTeamCloudValidationProvider(configuration =>
        {
            configuration
            .Register(Assembly.GetExecutingAssembly())
            .RegisterModelValidators();
        })
        .AddTeamCloudHttp()
        .AddTeamCloudAudit()
        .AddTeamCloudSecrets()
        .AddMvcCore()
        .AddNewtonsoftJson();

        builder.Services
        .AddTeamCloudAdapterProvider(configuration =>
        {
            configuration
            .Register <AzureResourceManagerAdapter>()
            .Register <AzureDevOpsAdapter>()
            .Register <GitHubAdapter>()
            .Register <KubernetesAdapter>();
        });

        var notificationSmtpOptions = builder.Services
                                      .BuildServiceProvider()
                                      .GetService <INotificationSmtpOptions>();

        if (!string.IsNullOrWhiteSpace(notificationSmtpOptions?.Host) &&
            !string.IsNullOrWhiteSpace(notificationSmtpOptions?.SenderAddress))
        {
            builder.Services.AddTeamCloudNotificationSmtpSender(notificationSmtpOptions);
        }

        var databaseOptions = builder.Services
                              .BuildServiceProvider()
                              .GetService <TeamCloudDatabaseOptions>();

        builder.Services
        .AddCosmosCache(options =>
        {
            options.ClientBuilder     = new CosmosClientBuilder(databaseOptions.ConnectionString);
            options.DatabaseName      = $"{databaseOptions.DatabaseName}Cache";
            options.ContainerName     = "DistributedCache";
            options.CreateIfNotExists = true;
        })
        .AddSingleton <IRepositoryCache, RepositoryCache>();

        if (configuration.TryBind <EncryptionOptions>("Encryption", out var encryptionOptions) && !string.IsNullOrEmpty(encryptionOptions.KeyStorage))
        {
            const string EncryptionContainerName = "encryption";

            new BlobContainerClient(encryptionOptions.KeyStorage, EncryptionContainerName)
            .CreateIfNotExistsAsync()
            .Wait();

            var dataProtectionBuilder = builder.Services
                                        .AddDataProtection()
                                        .SetApplicationName("TeamCloud")
                                        .PersistKeysToAzureBlobStorage(encryptionOptions.KeyStorage, EncryptionContainerName, "keys.xml");

            if (!string.IsNullOrEmpty(encryptionOptions.KeyVault))
            {
                //dataProtectionBuilder.ProtectKeysWithAzureKeyVault()
                throw new NotImplementedException();
            }
        }

        builder.Services
        .AddSingleton <IDocumentExpanderProvider>(serviceProvider => new DocumentExpanderProvider(serviceProvider))
        .AddSingleton <IDocumentExpander, DeploymentScopeExpander>()
        .AddSingleton <IDocumentExpander, ProjectExpander>()
        .AddSingleton <IDocumentExpander, ProjectIdentityExpander>()
        .AddSingleton <IDocumentExpander, ComponentTaskExpander>()
        .AddSingleton <IDocumentExpander, ComponentExpander>()
        .AddSingleton <IDocumentExpander, UserExpander>();

        builder.Services
        .AddSingleton <IDocumentSubscriptionProvider>(serviceProvider => new DocumentSubscriptionProvider(serviceProvider))
        .AddSingleton <IDocumentSubscription, DocumentNotificationSubscription>();

        builder.Services
        .AddSingleton <IOrganizationRepository, CosmosDbOrganizationRepository>()
        .AddSingleton <IUserRepository, CosmosDbUserRepository>()
        .AddSingleton <IDeploymentScopeRepository, CosmosDbDeploymentScopeRepository>()
        .AddSingleton <IProjectIdentityRepository, CosmosDbProjectIdentityRepository>()
        .AddSingleton <IProjectTemplateRepository, CosmosDbProjectTemplateRepository>()
        .AddSingleton <IComponentTemplateRepository, CosmosDbComponentTemplateRepository>()
        .AddSingleton <IComponentTaskRepository, CosmosDbComponentTaskRepository>()
        .AddSingleton <IProjectRepository, CosmosDbProjectRepository>()
        .AddSingleton <IComponentRepository, CosmosDbComponentRepository>()
        .AddSingleton <IScheduleRepository, CosmosDbScheduleRepository>()
        .AddSingleton <IRepositoryService, RepositoryService>();


        // CAUTION - don't register an orchstrator command handler with the generic
        // ICommandHandler<> interface. purpose of this interface is the
        // command specific implementation logic. to register and identifiy a command
        // handler use the non-generic ICommandHandler interface.

        var commandHandlerTypes = Assembly.GetExecutingAssembly()
                                  .GetTypes()
                                  .Where(t => t.IsClass && !t.IsAbstract && typeof(ICommandHandler).IsAssignableFrom(t));

        foreach (var commandHandlerType in commandHandlerTypes)
        {
            builder.Services.AddScoped(typeof(ICommandHandler), commandHandlerType);
        }
    }
Ejemplo n.º 22
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     builder.Services.AddScoped <IImageService, ImageService>();
     builder.Services.AddScoped <IAuthenticationService, AuthenticationService>();
 }
Ejemplo n.º 23
0
 public override void Configure(IFunctionsHostBuilder builder) =>
 builder.UseAutofacServiceProviderFactory(c => {
     c.Register(_ => new Defer <FuncCtx, ExecutionContext>(FuncCtx.LoadCtx)).SingleInstance();
     c.RegisterType <ApiBackend>();
     c.RegisterType <ApiRecfluence>();
 });
Ejemplo n.º 24
0
        /// <inheritdoc/>
        public override void Configure(IFunctionsHostBuilder builder)
        {
            // Add all options set from configuration values.
            builder.Services.AddOptions <SendFunctionOptions>()
            .Configure <IConfiguration>((companyCommunicatorSendFunctionOptions, configuration) =>
            {
                companyCommunicatorSendFunctionOptions.MaxNumberOfAttempts =
                    configuration.GetValue <int>("MaxNumberOfAttempts", 1);

                companyCommunicatorSendFunctionOptions.SendRetryDelayNumberOfSeconds =
                    configuration.GetValue <double>("SendRetryDelayNumberOfSeconds", 660);
            });
            builder.Services.AddOptions <BotOptions>()
            .Configure <IConfiguration>((botOptions, configuration) =>
            {
                botOptions.UserAppId =
                    configuration.GetValue <string>("UserAppId");

                botOptions.UserAppPassword =
                    configuration.GetValue <string>("UserAppPassword");
            });
            builder.Services.AddOptions <RepositoryOptions>()
            .Configure <IConfiguration>((repositoryOptions, configuration) =>
            {
                repositoryOptions.StorageAccountConnectionString =
                    configuration.GetValue <string>("StorageAccountConnectionString");

                // Defaulting this value to true because the main app should ensure all
                // tables exist. It is here as a possible configuration setting in
                // case it needs to be set differently.
                repositoryOptions.EnsureTableExists =
                    !configuration.GetValue <bool>("IsItExpectedThatTableAlreadyExists", true);
            });
            builder.Services.AddOptions <MessageQueueOptions>()
            .Configure <IConfiguration>((messageQueueOptions, configuration) =>
            {
                messageQueueOptions.ServiceBusConnection =
                    configuration.GetValue <string>("ServiceBusConnection");
            });

            builder.Services.AddLocalization();

            // Set current culture.
            var culture = Environment.GetEnvironmentVariable("i18n:DefaultCulture");

            CultureInfo.DefaultThreadCurrentCulture   = new CultureInfo(culture);
            CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(culture);

            // Add bot services.
            builder.Services.AddSingleton <UserAppCredentials>();
            builder.Services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>();
            builder.Services.AddSingleton <BotFrameworkHttpAdapter>();

            // Add teams services.
            builder.Services.AddTransient <IMessageService, MessageService>();

            // Add repositories.
            builder.Services.AddSingleton <ISendingNotificationDataRepository, SendingNotificationDataRepository>();
            builder.Services.AddSingleton <IGlobalSendingNotificationDataRepository, GlobalSendingNotificationDataRepository>();
            builder.Services.AddSingleton <ISentNotificationDataRepository, SentNotificationDataRepository>();

            // Add service bus message queues.
            builder.Services.AddSingleton <ISendQueue, SendQueue>();

            // Add the Notification service.
            builder.Services.AddTransient <INotificationService, NotificationService>();
        }
Ejemplo n.º 25
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     builder.AddSwashBuckle(Assembly.GetExecutingAssembly());
 }
Ejemplo n.º 26
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     // Make Azure App Configuration services and feature manager available through dependency injection
     builder.Services.AddAzureAppConfiguration();
     builder.Services.AddFeatureManagement();
 }
Ejemplo n.º 27
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     builder.Services
     .AddSerilogLogger(_configuration, _environmentName)
     .AddServiceBus(_configuration);
 }
Ejemplo n.º 28
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     builder.Services.AddSingleton <IMyService>((s) => {
         return(new myClass());
     });
 }
Ejemplo n.º 29
0
 public override void Configure(IFunctionsHostBuilder builder)
 {
     builder.Services.AddSingleton <IEventHubBroadCaster, EventHubBroadCaster>();
 }
Ejemplo n.º 30
0
 public static void Register(IFunctionsHostBuilder builder)
 {
     builder.Services.AddTransient <IEventProcessor, Service.EventProcessor>();
 }