예제 #1
0
        private static IBioWorldBuilder AddServiceClient <T>(this IBioWorldBuilder builder, string serviceName,
                                                             RestEaseOptions options, Action <IBioWorldBuilder> registerFabio)
            where T : class
        {
            if (!builder.TryRegister(RegistryName))
            {
                return(builder);
            }

            var clientName = typeof(T).ToString();

            switch (options.LoadBalancer?.ToLowerInvariant())
            {
            case "consul":
                builder.AddConsulHttpClient(clientName, serviceName);
                break;

            case "fabio":
                builder.AddFabioHttpClient(clientName, serviceName);
                break;

            default:
                ConfigureDefaultClient(builder.Services, clientName, serviceName, options);
                break;
            }

            ConfigureForwarder <T>(builder.Services, clientName);

            registerFabio(builder);

            return(builder);
        }
예제 #2
0
        public static IBioWorldBuilder AddConsul(this IBioWorldBuilder builder, ConsulOptions options,
                                                 HttpClientOptions httpClientOptions)
        {
            builder.Services.AddSingleton(options);
            if (!options.Enabled || !builder.TryRegister(RegistryName))
            {
                return(builder);
            }

            if (httpClientOptions.Type?.ToLowerInvariant() == "consul")
            {
                builder.Services.AddTransient <ConsulServiceDiscoveryMessageHandler>();
                builder.Services.AddHttpClient <IConsulHttpClient, ConsulHttpClient>("consul-http")
                .AddHttpMessageHandler <ConsulServiceDiscoveryMessageHandler>();
                builder.RemoveHttpClient();
                builder.Services.AddHttpClient <IHttpClient, ConsulHttpClient>("consul")
                .AddHttpMessageHandler <ConsulServiceDiscoveryMessageHandler>();
            }

            builder.Services.AddTransient <IConsulServicesRegistry, ConsulServicesRegistry>();
            var registration = builder.CreateConsulAgentRegistration(options);

            if (registration is null)
            {
                return(builder);
            }

            builder.Services.AddSingleton(registration);

            return(builder);
        }
예제 #3
0
        public static IBioWorldBuilder AddSwaggerDocs(this IBioWorldBuilder builder, SwaggerOptions options)
        {
            if (!options.Enabled || !builder.TryRegister(RegisterName))
            {
                return(builder);
            }

            builder.Services.AddSingleton(options);
            builder.Services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(options.Name, new OpenApiInfo()
                {
                    Title = options.Title, Version = options.Version
                });
                if (options.IncludeSecurity)
                {
                    c.AddSecurityDefinition("Bear", new OpenApiSecurityScheme()
                    {
                        Description =
                            "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                        Name = "Authorization",
                        In   = ParameterLocation.Header,
                        Type = SecuritySchemeType.ApiKey
                    });
                }
            });

            return(builder);
        }
예제 #4
0
        public static IBioWorldBuilder AddDistributedAccessTokenValidator(this IBioWorldBuilder builder)
        {
            if (!builder.TryRegister(RegistryName))
            {
                return(builder);
            }

            builder.Services.AddSingleton <IAccessTokenService, DistributedAccessTokenService>();
            return(builder);
        }
예제 #5
0
        public static IBioWorldBuilder AddMongo(this IBioWorldBuilder builder, MongoDbOptions mongoOptions,
                                                Type seederType = null, bool registerConventions = true)
        {
            if (!builder.TryRegister(RegistryName))
            {
                return(builder);
            }

            if (mongoOptions.SetRandomDatabaseSuffix)
            {
                var suffix = $"{Guid.NewGuid():N}";
                Console.WriteLine($"Setting a random MongoDB database suffix: '{suffix}'.");
                mongoOptions.Database = $"{mongoOptions.Database}_{suffix}";
            }

            builder.Services.AddSingleton(mongoOptions);
            builder.Services.AddSingleton <IMongoClient>(sp =>
            {
                var options = sp.GetService <MongoDbOptions>();
                return(new MongoClient(options.ConnectionString));
            });
            builder.Services.AddTransient(sp =>
            {
                var options = sp.GetService <MongoDbOptions>();
                var client  = sp.GetService <IMongoClient>();
                return(client.GetDatabase(options.Database));
            });
            builder.Services.AddTransient <IMongoDbInitializer, MongoDbInitializer>();
            builder.Services.AddTransient <IMongoSessionFactory, MongoSessionFactory>();

            if (seederType is null)
            {
                builder.Services.AddTransient <IMongoDbSeeder, MongoDbSeeder>();
            }
            else
            {
                builder.Services.AddTransient(typeof(IMongoDbSeeder), seederType);
            }

            builder.AddInitializer <IMongoDbInitializer>();
            if (registerConventions && !_conventionsRegistered)
            {
                RegisterConventions();
            }

            return(builder);
        }
예제 #6
0
        public static IBioWorldBuilder AddCertificateAuthentication(this IBioWorldBuilder builder,
                                                                    string sectionName = SectionName, Type permissionValidatorType = null)
        {
            var options = builder.GetOptions <SecurityOptions>(sectionName);

            builder.Services.AddSingleton(options);
            if (!builder.TryRegister(RegistryName))
            {
                return(builder);
            }

            if (options.Certificate is null || !options.Certificate.Enabled)
            {
                return(builder);
            }

            if (permissionValidatorType is { })
예제 #7
0
        private static IBioWorldBuilder AddJwt(this IBioWorldBuilder builder, JwtOptions options,
                                               Action <JwtBearerOptions> optionsFactory = null)
        {
            if (!builder.TryRegister(RegistryName))
            {
                return(builder);
            }

            builder.Services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            builder.Services.AddSingleton <IJwtHandler, JwtHandler>();
            builder.Services.AddSingleton <IAccessTokenService, InMemoryAccessTokenService>();
            builder.Services.AddTransient <AccessTokenValidatorMiddleware>();

            if (options.AuthenticationDisabled)
            {
                builder.Services.AddSingleton <IPolicyEvaluator, DisabledAuthenticationPolicyEvaluator>();
            }

            var tokenValidationParameters = new TokenValidationParameters
            {
                RequireAudience          = options.RequireAudience,
                ValidIssuer              = options.ValidIssuer,
                ValidIssuers             = options.ValidIssuers,
                ValidateActor            = options.ValidateActor,
                ValidAudience            = options.ValidAudience,
                ValidAudiences           = options.ValidAudiences,
                ValidateAudience         = options.ValidateAudience,
                ValidateIssuer           = options.ValidateIssuer,
                ValidateLifetime         = options.ValidateLifetime,
                ValidateTokenReplay      = options.ValidateTokenReplay,
                ValidateIssuerSigningKey = options.ValidateIssuerSigningKey,
                SaveSigninToken          = options.SaveSigninToken,
                RequireExpirationTime    = options.RequireExpirationTime,
                RequireSignedTokens      = options.RequireSignedTokens,
                ClockSkew = TimeSpan.Zero
            };

            if (!string.IsNullOrWhiteSpace(options.AuthenticationType))
            {
                tokenValidationParameters.AuthenticationType = options.AuthenticationType;
            }

            var hasCertificate = false;

            if (options.Certificate is { })
예제 #8
0
        public static IBioWorldBuilder AddRedis(this IBioWorldBuilder builder, RedisOptions options)
        {
            if (!builder.TryRegister(RegistryName))
            {
                return(builder);
            }

            builder.Services
            .AddSingleton(options)
            .AddSingleton <IConnectionMultiplexer>(sp => ConnectionMultiplexer.Connect(options.ConnectionString))
            .AddTransient(sp => sp.GetRequiredService <IConnectionMultiplexer>().GetDatabase(options.Database))
            .AddStackExchangeRedisCache(o =>
            {
                o.Configuration = options.ConnectionString;
                o.InstanceName  = options.Instance;
            });
            return(builder);
        }
예제 #9
0
        public static IBioWorldBuilder AddJaeger(this IBioWorldBuilder builder, JaegerOptions options,
                                                 string sectionName = SectionName, Action <IOpenTracingBuilder> openTracingBuilder = null)
        {
            if (Interlocked.Exchange(ref _initialized, 1) == 1)
            {
                return(builder);
            }

            builder.Services.AddSingleton(options);
            if (!options.Enabled)
            {
                var defaultTracer = BioworldDefaultTracer.Create();
                builder.Services.AddSingleton(defaultTracer);
                return(builder);
            }

            if (!builder.TryRegister(RegistryName))
            {
                return(builder);
            }

            if (options.ExcludePaths is { })
예제 #10
0
        public static IBioWorldBuilder AddHttpClient(this IBioWorldBuilder builder, string clientName = "bioworld",
                                                     IEnumerable <string> maskedRequestUrlParts       = null, string sectionName = SectionName,
                                                     Action <IHttpClientBuilder> httpClientBuilder    = null)
        {
            if (string.IsNullOrWhiteSpace(sectionName))
            {
                sectionName = SectionName;
            }

            if (!builder.TryRegister(RegistryName))
            {
                return(builder);
            }

            if (string.IsNullOrWhiteSpace(clientName))
            {
                throw new ArgumentException("HTTP client name cannot be empty.", nameof(clientName));
            }

            var options = builder.GetOptions <HttpClientOptions>(sectionName);

            if (maskedRequestUrlParts is { } && options.RequestMasking is { })
예제 #11
0
        private static IBioWorldBuilder AddFabio(this IBioWorldBuilder builder, FabioOptions fabioOptions,
                                                 HttpClientOptions httpClientOptions, Action <IBioWorldBuilder> registerConsul)
        {
            registerConsul(builder);
            builder.Services.AddSingleton(fabioOptions);

            if (!fabioOptions.Enabled || !builder.TryRegister(RegisterName))
            {
                return(builder);
            }

            if (httpClientOptions.Type?.ToLowerInvariant() == "fabio")
            {
                builder.Services.AddTransient <FabioMessageHandler>();
                builder.Services.AddHttpClient <IFabioHttpClient, FabioHttpClient>("fabio-http")
                .AddHttpMessageHandler <FabioMessageHandler>();

                builder.RemoveHttpClient();
                builder.Services.AddHttpClient <FabioMessageHandler>();
            }

            using var serviceProvider = builder.Services.BuildServiceProvider();
            var registration = serviceProvider.GetService <ServiceRegistration>();
            var tags         = GetFabioTags(registration.Name, fabioOptions.Service);

            if (registration.Tags is null)
            {
                registration.Tags = tags;
            }
            else
            {
                registration.Tags.AddRange(tags);
            }

            builder.Services.UpdateConsulRegistration(registration);

            return(builder);
        }
예제 #12
0
        private static IBioWorldBuilder AddRabbitMq <TContext>(this IBioWorldBuilder builder, RabbitMqOptions options,
                                                               Func <IRabbitMqPluginRegister, IRabbitMqPluginRegister> plugins, Action <IBioWorldBuilder> registerRedis)
            where TContext : class, new()
        {
            builder.Services.AddSingleton(options);
            builder.Services.AddSingleton <RawRabbitConfiguration>(options);
            if (!builder.TryRegister(RegistryName))
            {
                return(builder);
            }

            builder.Services.AddTransient <IBusPublisher, BusPublisher>();
            if (options.MessageProcessor?.Enabled == true)
            {
                switch (options.MessageProcessor.Type?.ToLowerInvariant())
                {
                case "redis":
                    registerRedis(builder);
                    builder.Services.AddTransient <IMessageProcessor, RedisMessageProcessor>();
                    break;

                default:
                    builder.Services.AddTransient <IMessageProcessor, InMemoryMessageProcessor>();
                    break;
                }
            }
            else
            {
                builder.Services.AddSingleton <IMessageProcessor, EmptyMessageProcessor>();
            }

            builder.Services.AddSingleton <ICorrelationContextAccessor>(new CorrelationContextAccessor());

            ConfigureBus <TContext>(builder, plugins);

            return(builder);
        }
예제 #13
0
        public static IBioWorldBuilder AddMessageOutbox(this IBioWorldBuilder builder,
                                                        Action <IMessageOutboxConfigurator> configure = null, string sectionName = SectionName)
        {
            if (string.IsNullOrWhiteSpace(sectionName))
            {
                sectionName = SectionName;
            }

            if (!builder.TryRegister(RegistryName))
            {
                return(builder);
            }

            var options = builder.GetOptions <OutboxOptions>(sectionName);

            builder.Services.AddSingleton(options);
            var configurator = new MessageOutboxConfigurator(builder, options);

            if (configure is null)
            {
                configurator.AddInMemory();
            }
            else
            {
                configure(configurator);
            }

            if (!options.Enabled)
            {
                return(builder);
            }

            builder.Services.AddHostedService <OutboxProcessor>();

            return(builder);
        }
예제 #14
0
        public static IBioWorldBuilder AddWebApi(this IBioWorldBuilder builder,
                                                 Action <IMvcCoreBuilder> configureMvc = null,
                                                 IJsonSerializer jsonSerializer        = null, string sectionName = SectionName)
        {
            if (string.IsNullOrWhiteSpace(sectionName))
            {
                sectionName = SectionName;
            }

            if (!builder.TryRegister(RegisterName))
            {
                return(builder);
            }

            if (jsonSerializer is null)
            {
                var factory = new Open.Serialization.Json.Newtonsoft.JsonSerializerFactory(new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver(),
                    Converters       = { new StringEnumConverter() }
                });
                jsonSerializer = factory.GetSerializer();
            }

            if (jsonSerializer.GetType().Namespace?.Contains("Newtonsoft") == true)
            {
                builder.Services.Configure <KestrelServerOptions>(o => o.AllowSynchronousIO = true);
                builder.Services.Configure <IISServerOptions>(o => o.AllowSynchronousIO     = true);
            }

            builder.Services.AddSingleton(jsonSerializer);
            builder.Services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            builder.Services.AddSingleton(new WebApiEndpointDefinitions());
            var options = builder.GetOptions <WebApiOptions>(sectionName);

            builder.Services.AddSingleton(options);
            _bindRequestFromRoute = options.BindRequestFromRoute;

            var mvcCoreBuilder = builder.Services.AddLogging().AddMvcCore();

            mvcCoreBuilder.AddMvcOptions(o =>
            {
                o.OutputFormatters.Clear();
                o.OutputFormatters.Add(new JsonOutputFormatter(jsonSerializer));
                o.InputFormatters.Clear();
                o.InputFormatters.Add(new JsonInputFormatter(jsonSerializer));
            })
            .AddDataAnnotations()
            .AddApiExplorer()
            .AddAuthorization();

            configureMvc?.Invoke(mvcCoreBuilder);
            builder.Services.Scan(s =>
                                  s.FromAssemblies(AppDomain.CurrentDomain.GetAssemblies()).AddClasses(c =>
                                                                                                       c.AssignableTo(typeof(IRequestHandler <,>)).WithoutAttribute(typeof(DecoratorAttribute)))
                                  .AsImplementedInterfaces().WithTransientLifetime());

            builder.Services.AddTransient <IRequestDispatcher, RequestDispatcher>();

            if (builder.Services.All(s => s.ServiceType != typeof(IExceptionToResponseMapper)))
            {
                builder.Services.AddTransient <IExceptionToResponseMapper, EmptyExceptionToResponseMapper>();
            }

            return(builder);
        }
예제 #15
0
        public static IBioWorldBuilder AddRabbitMq(this IBioWorldBuilder builder, string sectionName = SectionName,
                                                   Func <IRabbitMqPluginsRegistry, IRabbitMqPluginsRegistry> plugins = null,
                                                   Action <ConnectionFactory> connectionFactoryConfigurator          = null)
        {
            if (string.IsNullOrWhiteSpace(sectionName))
            {
                sectionName = SectionName;
            }

            var options = builder.GetOptions <RabbitMqOptions>(sectionName);

            builder.Services.AddSingleton(options);
            if (!builder.TryRegister(RegistryName))
            {
                return(builder);
            }

            if (options.HostNames is null || !options.HostNames.Any())
            {
                throw new ArgumentException("RabbitMQ hostnames are not specified.", nameof(options.HostNames));
            }

            ILogger <IRabbitMqClient> logger;

            using (var serviceProvider = builder.Services.BuildServiceProvider())
            {
                logger = serviceProvider.GetService <ILogger <IRabbitMqClient> >();
            }

            builder.Services.AddSingleton <IContextProvider, ContextProvider>();
            builder.Services.AddSingleton <ICorrelationContextAccessor>(new CorrelationContextAccessor());
            builder.Services.AddSingleton <IMessagePropertiesAccessor>(new MessagePropertiesAccessor());
            builder.Services.AddSingleton <IConventionsBuilder, ConventionsBuilder>();
            builder.Services.AddSingleton <IConventionsProvider, ConventionsProvider>();
            builder.Services.AddSingleton <IConventionsRegistry, ConventionsRegistry>();
            builder.Services.AddSingleton <IRabbitMqSerializer, NewtonsoftJsonRabbitMqSerializer>();
            builder.Services.AddSingleton <IRabbitMqClient, RabbitMqClient>();
            builder.Services.AddSingleton <IBusPublisher, RabbitMqPublisher>();
            builder.Services.AddSingleton <IBusSubscriber, RabbitMqSubscriber>();
            builder.Services.AddTransient <RabbitMqExchangeInitializer>();
            builder.Services.AddHostedService <RabbitMqHostedService>();
            builder.AddInitializer <RabbitMqExchangeInitializer>();

            var pluginsRegistry = new RabbitMqPluginsRegistry();

            builder.Services.AddSingleton <IRabbitMqPluginsRegistryAccessor>(pluginsRegistry);
            builder.Services.AddSingleton <IRabbitMqPluginsExecutor, RabbitMqPluginsExecutor>();
            plugins?.Invoke(pluginsRegistry);

            var connectionFactory = new ConnectionFactory
            {
                Port                         = options.Port,
                VirtualHost                  = options.VirtualHost,
                UserName                     = options.Username,
                Password                     = options.Password,
                RequestedHeartbeat           = options.RequestedHeartbeat,
                RequestedConnectionTimeout   = options.RequestedConnectionTimeout,
                SocketReadTimeout            = options.SocketReadTimeout,
                SocketWriteTimeout           = options.SocketWriteTimeout,
                RequestedChannelMax          = options.RequestedChannelMax,
                RequestedFrameMax            = options.RequestedFrameMax,
                UseBackgroundThreadsForIO    = options.UseBackgroundThreadsForIO,
                DispatchConsumersAsync       = true,
                ContinuationTimeout          = options.ContinuationTimeout,
                HandshakeContinuationTimeout = options.HandshakeContinuationTimeout,
                NetworkRecoveryInterval      = options.NetworkRecoveryInterval,
                Ssl = options.Ssl is null
                    ? new SslOption()
                    : new SslOption(options.Ssl.ServerName, options.Ssl.CertificatePath, options.Ssl.Enabled)
            };

            ConfigureSsl(connectionFactory, options, logger);
            connectionFactoryConfigurator?.Invoke(connectionFactory);

            logger.LogDebug($"Connecting to RabbitMQ: '{string.Join(", ", options.HostNames)}'...");
            var connection = connectionFactory.CreateConnection(options.HostNames.ToList(), options.ConnectionName);

            logger.LogDebug($"Connected to RabbitMQ: '{string.Join(", ", options.HostNames)}'.");
            builder.Services.AddSingleton(connection);

            ((IRabbitMqPluginsRegistryAccessor)pluginsRegistry).Get().ToList().ForEach(p =>
                                                                                       builder.Services.AddTransient(p.PluginType));

            return(builder);
        }