Beispiel #1
0
        private static void AddServiceDependency(IServiceCollection services)
        {
            var factory = new Open.Serialization.Json.Newtonsoft.JsonSerializerFactory(new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Converters       = { new StringEnumConverter(true) }
            });
            var jsonSerializer = factory.GetSerializer();

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

            services.AddSingleton(jsonSerializer);
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <IUserContext, UserContext>();
            services.AddSingleton <IPasswordService, PasswordService>();
            services.AddSingleton <IPasswordHasher <IPasswordService>, PasswordHasher <IPasswordService> >();
            services.AddTransient <IIdentityService, IdentityService>();
            services.AddTransient <IUserRepository, UserRepository>();
            services.AddTransient <IMessageRepository, MessageRepository>();
            services.AddTransient <IBlockUserRepository, BlockUserRepository>();
        }
        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);
        }
Beispiel #3
0
        public static IConveyBuilder AddWebApi(this IConveyBuilder builder, Action <IMvcCoreBuilder> configureMvc = null,
                                               IJsonSerializer jsonSerializer = null, string sectionName = SectionName)
        {
            if (!builder.TryRegister(RegistryName))
            {
                return(builder);
            }

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

            if (jsonSerializer.GetType().Namespace?.Contains("Newtonsoft") == true)
            {
                builder.Services.Configure <KestrelServerOptions>(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 <,>)))
                                  .AsImplementedInterfaces()
                                  .WithTransientLifetime());

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

            return(builder);
        }
Beispiel #4
0
        public static IJsonSerializer GetJsonSerializer()
        {
            var factory = new Open.Serialization.Json.Newtonsoft.JsonSerializerFactory(new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });

            return(factory.GetSerializer());
        }
Beispiel #5
0
        public static IJsonSerializer GetDefaultJsonSerializer()
        {
            var factory = new Open.Serialization.Json.Newtonsoft.JsonSerializerFactory(new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Converters       = { new StringEnumConverter(true) }
            });

            return(factory.GetSerializer());
        }
        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);
Beispiel #7
0
        public static IServiceCollection AddWebApi(this IServiceCollection serviceCollection, Action <IMvcCoreBuilder> configureMvc = null,
                                                   IJsonSerializer jsonSerializer = null, string webApiSectionName = WebApiSectionName, string appSectionName = AppsectionName)
        {
            serviceCollection.AddSingleton <IServiceId, ServiceId>();
            serviceCollection.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            if (string.IsNullOrWhiteSpace(appSectionName))
            {
                appSectionName = AppsectionName;
            }

            var options = serviceCollection.GetOptions <AppOptions>(appSectionName);

            serviceCollection.AddMemoryCache();
            serviceCollection.AddSingleton(options);

            if (options.DisplayBanner && string.IsNullOrWhiteSpace(options.Name) == false)
            {
                var version = options.DisplayVersion ? $" {options.Version}" : string.Empty;
                Console.WriteLine(Figgle.FiggleFonts.Doom.Render($"{options.Name}{version}"));
            }

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

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

            serviceCollection.AddSingleton(jsonSerializer);
            serviceCollection.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            serviceCollection.AddSingleton(new WebApiEndpointDefinitions());
            var webApiOptions = serviceCollection.GetOptions <WebApiOptions>(webApiSectionName);

            serviceCollection.AddSingleton(options);
            _bindRequestFromRoute = webApiOptions.BindRequestFromRoute;

            var mvcCoreBuilder = serviceCollection
                                 .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);

            serviceCollection.Scan(s =>
                                   s.FromAssemblies(AppDomain.CurrentDomain.GetAssemblies())
                                   .AddClasses(c => c.AssignableTo(typeof(IRequestHandler <,>)))
                                   .AsImplementedInterfaces()
                                   .WithTransientLifetime());

            serviceCollection.AddTransient <IRequestDispatcher, RequestDispatcher>();
            serviceCollection.AddErrorHandler <EmptyExceptionToResponseMapper>();

            return(serviceCollection);
        }
Beispiel #8
0
        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);
        }