コード例 #1
0
ファイル: Extensions.cs プロジェクト: DanielMrowca/HoneyComb
        public static IHoneyCombBuilder AddWebApi(this IHoneyCombBuilder builder, Action <IMvcCoreBuilder> configureMvc = null,
                                                  IJsonSerializer jsonSerializer = null)
        {
            var jsonSerializerIsRegistered = builder.Services.Any(x => x.ServiceType == typeof(IJsonSerializer));

            if (!jsonSerializerIsRegistered)
            {
                if (jsonSerializer is null)
                {
                    jsonSerializer = GetDefaultJsonSerializer();
                }

                builder.Services.AddSingleton(jsonSerializer);
            }

            builder.Services.AddSingleton(jsonSerializer);

            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));
            //});

            configureMvc?.Invoke(mvcCoreBuilder);

            return(builder);
        }
コード例 #2
0
        public static IHoneyCombBuilder AddWebApi(this IHoneyCombBuilder builder, Action <IMvcCoreBuilder> configureMvc = null,
                                                  IJsonSerializer jsonSerializer = null)
        {
            if (jsonSerializer is null)
            {
                var factory = new Open.Serialization.Json.Newtonsoft.JsonSerializerFactory(new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver(),
                    Converters       = { new StringEnumConverter(true) }
                });
                jsonSerializer = factory.GetSerializer();
            }

            builder.Services.AddSingleton(jsonSerializer);

            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));
            //});

            configureMvc?.Invoke(mvcCoreBuilder);

            return(builder);
        }
コード例 #3
0
        public static IHoneyCombBuilder AddMongoRepository <TEntity, TKey>(this IHoneyCombBuilder builder, string collectionName,
                                                                           Action <List <CreateIndexModel <TEntity> >, IndexKeysDefinitionBuilder <TEntity> > indexBuilder = null)
            where TEntity : IIdentifiable <TKey>
        {
            var indexes         = new List <CreateIndexModel <TEntity> >();
            var indexKeyBuilder = Builders <TEntity> .IndexKeys;

            indexBuilder?.Invoke(indexes, indexKeyBuilder);
            if (indexes.Count > 0)
            {
                builder.Services.AddSingleton <IInitializer>(sp =>
                {
                    var db = sp.CreateScope().ServiceProvider.GetService <IMongoDatabase>();
                    return(new MongoIndexesInitializer <TEntity, TKey>(db, collectionName, indexes));
                });
            }

            builder.Services.AddScoped <IMongoRepository <TEntity, TKey> >(sp =>
            {
                var context = sp.GetService <IMongoContext>();
                return(new MongoRepository <TEntity, TKey>(context, collectionName));
            });

            return(builder);
        }
コード例 #4
0
 public ConnectionWithRetryFactory(ConnectionFactory connectionFactory,
                                   RabbitMqOptions options, IHoneyCombBuilder honeyCombBuilder)
 {
     _connectionFactory = connectionFactory;
     _options           = options;
     _honeyCombBuilder  = honeyCombBuilder;
 }
コード例 #5
0
ファイル: Extensions.cs プロジェクト: DanielMrowca/HoneyComb
        public static IHoneyCombBuilder AddRabbitMQ(this IHoneyCombBuilder builder, string sectionName, string connectionName = null, string prefixQueueName = null, int retriesCountOnConnectingFailed = -1)
        {
            var options = builder.GetSettings <RabbitMqOptions>(sectionName);

            options.ConnectionName = string.IsNullOrWhiteSpace(connectionName) ? options.ConnectionName : connectionName;
            var queueIdentProvider = string.IsNullOrWhiteSpace(prefixQueueName) ? null : new RabbitQueueIdentifierProvider(prefixQueueName);

            return(AddRabbitMQ(builder, options, null, null, queueIdentProvider, retriesCountOnConnectingFailed));
        }
コード例 #6
0
        private static void AddMongoContext(this IHoneyCombBuilder builder)
        {
            var sp = builder.Services.BuildServiceProvider();

            var mongoContext = new MongoTransactionalContext(sp.GetRequiredService <IMongoDatabase>(), sp.GetRequiredService <IMongoClient>());

            builder.Services.AddScoped <IMongoContext>(sp => mongoContext);
            builder.Services.AddScoped <ITransactionScope>(sp => mongoContext);
        }
コード例 #7
0
 public static T GetSettings <T>(this IHoneyCombBuilder builder, string sectionName)
     where T : new()
 {
     using (var serviceProvicer = builder.Services.BuildServiceProvider())
     {
         var config = serviceProvicer.GetRequiredService <IConfiguration>();
         return(config.GetSettings <T>(sectionName));
     }
 }
コード例 #8
0
        public static IHoneyCombBuilder AddMongoRepository <TEntity, TKey>(this IHoneyCombBuilder builder, string collectionName, string[] index = null)
            where TEntity : IIdentifiable <TKey>
        {
            builder.Services.AddTransient <IMongoRepository <TEntity, TKey> >(sp =>
            {
                var db = sp.GetService <IMongoDatabase>();
                return(new MongoRepository <TEntity, TKey>(db, collectionName, index));
            });

            return(builder);
        }
コード例 #9
0
        public static IHoneyCombBuilder AddRequestDecompression(this IHoneyCombBuilder builder, Action <RequestDecompressionOptions> configureOptions = null)
        {
            var options = new RequestDecompressionOptions();

            configureOptions?.Invoke(options);

            builder.Services.AddSingleton(options);
            builder.Services.AddSingleton <IRequestDecompressionProvider, RequestDecompressionProvider>();

            return(builder);
        }
コード例 #10
0
        public static IHoneyCombBuilder AddEventHandlers(this IHoneyCombBuilder builder)
        {
            builder.Services.Scan(s => s
                                  .FromExecutingAssembly()
                                  .FromCallingAssembly()
                                  .FromApplicationDependencies()
                                  .AddClasses(c => c.AssignableTo(typeof(IEventHandler <>)))
                                  .AsImplementedInterfaces()
                                  .WithTransientLifetime());

            return(builder);
        }
コード例 #11
0
        public static IHoneyCombBuilder AddWebApiDispatcher(this IHoneyCombBuilder builder)
        {
            builder.AddWebApi();

            builder.Services.Scan(s => s
                                  .FromExecutingAssembly()
                                  .FromCallingAssembly()
                                  .FromApplicationDependencies()
                                  .AddClasses(c => c.AssignableTo(typeof(IHttpRequestHandler <>)))
                                  .AddClasses(c => c.AssignableTo(typeof(IHttpRequestHandler <,>)))
                                  .AsImplementedInterfaces()
                                  .WithTransientLifetime());

            builder.Services.AddSingleton <IHttpRequestDispatcher, HttpRequestDispatcher>();
            return(builder);
        }
コード例 #12
0
        public static IHoneyCombBuilder AddMongo(this IHoneyCombBuilder builder, MongoDbOptions dbOptions)
        {
            builder.Services.AddSingleton(dbOptions);
            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));
            });

            return(builder);
        }
コード例 #13
0
ファイル: Extensions.cs プロジェクト: DanielMrowca/HoneyComb
        public static IHoneyCombBuilder AddHttpClient(this IHoneyCombBuilder builder, string clientName = "honeyComb", string sectionName = SectionName)
        {
            if (string.IsNullOrWhiteSpace(sectionName))
            {
                sectionName = SectionName;
            }

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

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

            builder.Services.AddSingleton(options);
            builder.Services.AddHttpClient <IHttpClient, HoneyCombHttpClient>(clientName);

            return(builder);
        }
コード例 #14
0
        public static IHoneyCombBuilder AddRabbitMQ(this IHoneyCombBuilder builder, RabbitMqOptions options, IJsonSerializer jsonSerializer = null)
        {
            if (jsonSerializer is null)
            {
                var factory = new Open.Serialization.Json.Newtonsoft.JsonSerializerFactory(new JsonSerializerSettings
                {
                    ContractResolver  = new CamelCasePropertyNamesContractResolver(),
                    NullValueHandling = NullValueHandling.Ignore
                });
                jsonSerializer = factory.GetSerializer();
            }

            builder.Services.AddSingleton(jsonSerializer);
            builder.Services.AddSingleton(options);
            builder.Services.AddSingleton <IConventionBuilder, UnderscoreCaseConventionBuilder>();
            builder.Services.AddSingleton <IConventionProvider, ConventionProvider>();
            builder.Services.AddSingleton <IRabbitMqClient, RabbitMqClient>();
            builder.Services.AddSingleton <IBusPublisher, RabbitMqPublisher>();
            builder.Services.AddSingleton <IBusSubscriber, RabbitMqSubscriber>();

            builder.Services.AddTransient <RabbitMqExchangeInitializer>();
            builder.AddInitializer <RabbitMqExchangeInitializer>();

            var connection = new ConnectionFactory
            {
                Port        = options.Port,
                VirtualHost = options.VirtualHost,
                UserName    = options.Username,
                Password    = options.Password,
                RequestedConnectionTimeout = options.RequestedConnectionTimeout,
                SocketReadTimeout          = options.SocketReadTimeout,
                SocketWriteTimeout         = options.SocketWriteTimeout,
                RequestedChannelMax        = options.RequestedChannelMax,
                RequestedFrameMax          = options.RequestedFrameMax,
                RequestedHeartbeat         = options.RequestedHeartbeat,
                UseBackgroundThreadsForIO  = options.UseBackgroundThreadsForIO,
                DispatchConsumersAsync     = true,
                Ssl = options.Ssl is null
                    ? new SslOption()
                    : new SslOption(options.Ssl.ServerName, options.Ssl.CertificatePath, options.Ssl.Enabled)
            }.CreateConnection(options.HostNames.ToList(), options.ConnectionName);
コード例 #15
0
        public static IHoneyCombBuilder AddMongo(this IHoneyCombBuilder builder, MongoDbOptions dbOptions)
        {
            builder.Services.AddSingleton(dbOptions);
            builder.Services.AddSingleton <IMongoClient>(sp =>
            {
                var options = sp.GetService <MongoDbOptions>();
                return(new MongoClient(options.ConnectionString));
            });

            builder.Services.AddScoped(sp =>
            {
                var options = sp.GetService <MongoDbOptions>();
                var client  = sp.GetService <IMongoClient>();
                return(client.GetDatabase(options.Database));
            });

            // Required for transactional mongo repository
            builder.AddMongoContext();

            return(builder);
        }
コード例 #16
0
        public static IHoneyCombBuilder AddEventHandlers(this IHoneyCombBuilder builder)
        {
            builder.Services.Scan(s => s
                                  .FromAssemblies(AppDomain.CurrentDomain.GetAssemblies())
                                  .AddClasses(c =>
            {
                c.AssignableTo(typeof(IEventHandler <>));
                c.WithoutAttribute <AutoRegisterAttribute>();
            })
                                  .AsImplementedInterfaces()
                                  .WithTransientLifetime()

                                  .AddClasses(c =>
            {
                c.AssignableTo(typeof(IEventHandler <>));
                c.WithAttribute <AutoRegisterAttribute>(x => x.AutoRegister);
            })
                                  .AsImplementedInterfaces()
                                  .WithTransientLifetime());

            return(builder);
        }
コード例 #17
0
        public static IHoneyCombBuilder AddMongoRepositoryWithSequentialIndex <TDocument, TKey>(this IHoneyCombBuilder builder, string collectionName,
                                                                                                Action <List <CreateIndexModel <TDocument> >, IndexKeysDefinitionBuilder <TDocument> > indexBuilder = null)
            where TDocument : ISequentialIndex <TKey>
        {
            builder.AddMongoRepository <TDocument, TKey>(collectionName, indexBuilder);
            builder.Services.Decorate <IMongoRepository <TDocument, TKey>, MongoRepositoryWithSequentialIndexDecorator <TDocument, TKey> >();
            builder.Services.AddSingleton <ISequentialIndexCache, SequentialIndexCache>();
            builder.Services.AddScoped <ISequentialIndexProvider <TDocument, TKey> >(sp =>
            {
                var db    = sp.GetService <IMongoContext>();
                var cache = sp.GetService <ISequentialIndexCache>();
                return(new SequentialIndexProvider <TDocument, TKey>(db, collectionName, cache));
            });

            builder.Services.AddSingleton <IInitializer>(sp => sp.GetService <ISequentialIndexProvider <TDocument, TKey> >());
            return(builder);
        }
コード例 #18
0
        public static IHoneyCombBuilder AddMongo(this IHoneyCombBuilder builder, string settingsSection)
        {
            var options = builder.GetSettings <MongoDbOptions>(settingsSection);

            return(builder.AddMongo(options));
        }
コード例 #19
0
ファイル: Extensions.cs プロジェクト: DanielMrowca/HoneyComb
        public static IHoneyCombBuilder AddRabbitMQ(this IHoneyCombBuilder builder, RabbitMqOptions options, IJsonSerializer jsonSerializer = null,
                                                    IConventionBuilder conventionBuilder = null, IRabbitQueuePrefixProvider rabbitQueueIdentifierProvider = null, int retriesCountOnConnectingFailed = -1)
        {
            var jsonSerializerIsRegistered = builder.Services.Any(x => x.ServiceType == typeof(IJsonSerializer));

            if (!jsonSerializerIsRegistered)
            {
                if (jsonSerializer is null)
                {
                    var factory = new Open.Serialization.Json.Newtonsoft.JsonSerializerFactory(new JsonSerializerSettings
                    {
                        ContractResolver  = new CamelCasePropertyNamesContractResolver(),
                        NullValueHandling = NullValueHandling.Ignore
                    });
                    jsonSerializer = factory.GetSerializer();
                }
                builder.Services.AddSingleton(jsonSerializer);
            }

            var queueIdentIsRegistered = builder.Services.Any(x => x.ServiceType == typeof(IRabbitQueuePrefixProvider));

            if (!queueIdentIsRegistered)
            {
                if (rabbitQueueIdentifierProvider is null)
                {
                    builder.Services.AddSingleton <IRabbitQueuePrefixProvider, RabbitQueueIdentifierProvider>();
                }
                else
                {
                    builder.Services.AddSingleton(rabbitQueueIdentifierProvider);
                }
            }

            builder.Services.AddSingleton(options);
            builder.Services.AddSingleton <IConventionBuilder, UnderscoreCaseConventionBuilder>();

            if (conventionBuilder is null)
            {
                builder.Services.AddSingleton <IConventionProvider, ConventionProvider>();
            }
            else
            {
                builder.Services.AddSingleton(conventionBuilder);
            }

            builder.Services.AddSingleton <IRabbitMqClient, RabbitMqClient>();
            builder.Services.AddSingleton <IBusPublisher, RabbitMqPublisher>();
            builder.Services.AddSingleton <IBusSubscriber, RabbitMqSubscriber>();

            builder.Services.AddTransient <IInitializer, RabbitMqExchangeInitializer>();

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


            builder.Services.AddSingleton(connectionFactory);
            builder.Services.AddSingleton <IConnectionFactory>(new ConnectionWithRetryFactory(connectionFactory, options, builder));


            //var policyBuilder = Policy.Handle<Exception>();
            //RetryPolicy retryPolicy = null;

            //if (retriesCountOnConnectingFailed < 0)
            //    retryPolicy = policyBuilder.WaitAndRetryForever(r => TimeSpan.FromSeconds(3 * r), OnConnectionException);
            //else
            //    retryPolicy = policyBuilder.WaitAndRetry(retriesCountOnConnectingFailed, r => TimeSpan.FromSeconds(3 * r), OnConnectionException);

            //var connection = retryPolicy.ExecuteAndCapture(() => connectionFactory.CreateConnection(options.HostNames.ToList(), options.ConnectionName));

            //void OnConnectionException(Exception ex, TimeSpan ts)
            //{
            //    var logger = builder.Services.BuildServiceProvider().GetRequiredService<ILogger<IConnection>>();
            //    logger.LogError(ex, $"Error while connecting to RabbitMq. {ex.Message}");
            //}

            //builder.Services.AddSingleton(connection);


            return(builder);
        }
コード例 #20
0
 public static IHoneyCombBuilder AddEventDispatcher(this IHoneyCombBuilder builder)
 {
     builder.Services.AddSingleton <IEventDispatcher, EventDispatcher>();
     return(builder);
 }
コード例 #21
0
ファイル: Extensions.cs プロジェクト: DanielMrowca/HoneyComb
 public static IHoneyCombBuilder AddErrorHandler <T>(this IHoneyCombBuilder builder) where T : class, IExceptionToResponseMapper
 {
     builder.Services.AddTransient <ErrorHandlerMiddleware>();
     builder.Services.AddTransient <IExceptionToResponseMapper, T>();
     return(builder);
 }
コード例 #22
0
 public static IHoneyCombBuilder AddCommandDispatcher(this IHoneyCombBuilder builder)
 {
     builder.Services.AddSingleton <ICommandDispatcher, CommandDispatcher>();
     return(builder);
 }
コード例 #23
0
ファイル: Extensions.cs プロジェクト: DanielMrowca/HoneyComb
 public static IHoneyCombBuilder AddDefaultJsonSerializer(this IHoneyCombBuilder builder)
 {
     builder.Services.AddSingleton(GetDefaultJsonSerializer());
     return(builder);
 }
コード例 #24
0
 public static IHoneyCombBuilder AddInitializer <T>(this IHoneyCombBuilder builder) where T : class, IInitializer
 {
     builder.Services.AddSingleton <IInitializer, T>();
     return(builder);
 }