コード例 #1
0
        private static IDictionary <string, IHttpClientBuilder> UseMultipleClients(this Container services, IConfiguration configuration, IDictionary <string, TokenFlow> clients)
        {
            var collection = new ServiceCollection();

            services.UseHttpApiDefaults(collection);
            var builders       = new Dictionary <string, IHttpClientBuilder>();
            var clientBuilders = new List <Registration>();

            foreach (KeyValuePair <string, TokenFlow> client in clients)
            {
                string    clientName = client.Key;
                TokenFlow tokenFlow  = client.Value;

                IClientConfiguration clientConfiguration = configuration.GetSection(clientName).Get <ClientConfiguration>();
                Validator.ValidateObject(clientConfiguration, new ValidationContext(clientConfiguration), true);

                builders.Add(clientName, services.SetupClient(collection, clientName, clientConfiguration, tokenFlow));


                clientBuilders.Add(Lifestyle.Singleton.CreateRegistration(() => new CtpClient(services.GetService <IHttpClientFactory>(), services.GetService <IHttpApiCommandFactory>(), services.GetService <ISerializerService>(), services.GetService <IUserAgentProvider>())
                {
                    Name = clientName
                }, services));
            }
            services.RegisterCollection <IClient>(clientBuilders);
            services.Register <IHttpClientFactory>(() => collection.BuildServiceProvider().GetService <IHttpClientFactory>(), Lifestyle.Singleton);

            return(builders);
        }
        private static IDictionary <string, IHttpClientBuilder> UseSingleClient(this Container services, IConfiguration configuration, string clientName, TokenFlow tokenFlow)
        {
            var collection = new ServiceCollection();

            services.UseHttpApiDefaults();

            var configurationSection = configuration.GetSection(clientName);
            IClientConfiguration clientConfiguration = configurationSection.Get <ClientConfiguration>();

            Validator.ValidateObject(clientConfiguration, new ValidationContext(clientConfiguration), true);

            var builders = new ConcurrentDictionary <string, IHttpClientBuilder>();

            builders.TryAdd(clientName, services.SetupClient(collection, clientName, clientConfiguration, tokenFlow));

            services.Register <IClient>(() => new CtpClient(collection.BuildServiceProvider().GetService <IHttpClientFactory>(), services.GetService <IHttpApiCommandFactory>(), services.GetService <ISerializerService>(), services.GetService <IUserAgentProvider>())
            {
                Name = clientName
            }, Lifestyle.Singleton);

            collection.AddHttpClient(DefaultClientNames.Authorization);
            services.UseTokenProviders(collection.BuildServiceProvider().GetService <IHttpClientFactory>());

            return(builders);
        }