Esempio n. 1
0
        public static IMergenBuilder AddSwaggerDocs(this IMergenBuilder builder, string projectName = SectionName)
        {
            builder.Services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = projectName, Version = "v1"
                });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey,
                    Scheme      = "Bearer"
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme, Id = "Bearer"
                            }
                        },
                        new string[] {}
                    }
                });
            });
            return(builder);
        }
Esempio n. 2
0
        public static IMergenBuilder AddDefaultMessageBox(this IMergenBuilder serviceCollection)
        {
            serviceCollection.Services.AddSingleton <IMessageOutbox, DefaultMessageOutbox>();
            serviceCollection.Services.AddSingleton <IMessageInbox, DefaultMessageInbox>();

            return(serviceCollection);
        }
Esempio n. 3
0
        public static TModel GetOptions <TModel>(this IMergenBuilder builder, string settingsSectionName)
            where TModel : new()
        {
            using var serviceProvider = builder.Services.BuildServiceProvider();
            var configuration = serviceProvider.GetService <IConfiguration>();

            return(configuration.GetOptions <TModel>(settingsSectionName));
        }
Esempio n. 4
0
        public static IMergenBuilder AddWebApiSwaggerDocs(this IMergenBuilder builder, string sectionName = SectionName)
        {
            if (string.IsNullOrWhiteSpace(sectionName))
            {
                sectionName = SectionName;
            }

            return(builder.AddWebApiSwaggerDocs(b => b.AddSwaggerDocs(sectionName)));
        }
Esempio n. 5
0
        public static IMergenBuilder AddIntegrationEventHandlers(this IMergenBuilder builder)
        {
            builder.Services.Scan(s =>
                                  s.FromAssemblies(AppDomain.CurrentDomain.GetAssemblies())
                                  .AddClasses(c => c.AssignableTo(typeof(IIntegrationEventHandler <>))
                                              .WithoutAttribute(typeof(DecoratorAttribute)))
                                  .AsImplementedInterfaces()
                                  .WithTransientLifetime());
            builder.Services.AddSingleton <IIntegrationEventSender, IntegrationEventSender>();

            builder.AddDefaultBusPublisher();
            builder.AddDefaultMessageBox();

            return(builder);
        }
Esempio n. 6
0
        private static void AddHandler(IMergenBuilder builder, Type type)
        {
            object[] attributes = type.GetCustomAttributes(false);

            List <Type> pipeline = attributes
                                   .Select(t => t.GetType())
                                   .Concat(new[] { type })
                                   .Reverse()
                                   .ToList();

            Type interfaceType = type.GetInterfaces().Single(IsHandlerInterface);
            Func <IServiceProvider, object> factory = BuildPipeline(pipeline, interfaceType);

            builder.Services.AddTransient(interfaceType, factory);
        }
Esempio n. 7
0
        public static IMergenBuilder AddCommandHandlers(this IMergenBuilder builder, Assembly assembly)
        {
            //builder.Services.AddMediatR(Assembly.GetExecutingAssembly());
            //builder.Services.AddMediatorCommandsHandlers(assembly);
            builder.Services.Scan(s => s.FromAssemblies(assembly)
                                  .AddClasses(classes => classes.AssignableTo(typeof(ICommandHandler <>))
                                              .WithoutAttribute(typeof(DecoratorAttribute)))
                                  .AsImplementedInterfaces()
                                  .WithScopedLifetime()
                                  .AddClasses(classes => classes.AssignableTo(typeof(ICommandHandler <,>))
                                              .WithoutAttribute(typeof(DecoratorAttribute)))
                                  .AsImplementedInterfaces()
                                  .WithScopedLifetime()
                                  );

            builder.Services.AddScoped <ICommandSender, CommandSender>();
            return(builder);

            #region Old Builder

            //builder.Services.AddMediatR(Assembly.GetExecutingAssembly());
            //bool IsEventHandler(Type i) => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICommandHandler<,>);

            //if (projectAssembly == null) throw new ExecutionEngineException("dll type must be call");

            ////sadece cammandlar alınmalı
            //var commandHandler = Assembly.GetAssembly(projectAssembly).GetExportedTypes()
            //    .Where(t => t.GetInterfaces().Any(IsEventHandler))
            //    .ToList();

            //if (!commandHandler.Any()) return builder;

            //bool IsRequestHandler(Type i) => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IRequestHandler<,>);

            //var commands = commandHandler.Where(t => t.GetInterfaces().Any(IsRequestHandler));

            //foreach (var type in commands)
            //{
            //    AddHandler(builder, type);
            //}
            //builder.Services.AddSingleton<ICommandSender, CommandSender>();


            #endregion
        }
Esempio n. 8
0
        public static IMergenBuilder AddMongo(this IMergenBuilder serviceCollection, string sectionName = SectionName)
        {
            if (string.IsNullOrWhiteSpace(sectionName))
            {
                sectionName = SectionName;
            }

            var configuration = serviceCollection.Services.BuildServiceProvider().GetService <IConfiguration>();

            var options = configuration.GetSection(sectionName).Get <MongoOptions>();

            serviceCollection.Services.AddSingleton(options);

            if (string.IsNullOrEmpty(options.HostName) || string.IsNullOrEmpty(options.Port))
            {
                throw new ArgumentException("MongoDB hostname/port is not specified.");
            }

            if (string.IsNullOrEmpty(options.UserName) || string.IsNullOrEmpty(options.Password))
            {
                throw new ArgumentException("MongoDB username/password is not specified.");
            }

            if (string.IsNullOrEmpty(options.Database))
            {
                throw new ArgumentException("MongoDB Database is not specified.", nameof(options.Database));
            }

            var connectionString = $"mongodb://{options.UserName}:{options.Password}@{options.HostName}:{options.Port}/{options.Database}";

            serviceCollection.Services.AddSingleton <IMongoClient>(sp =>
            {
                return(new MongoClient(connectionString));
            });

            serviceCollection.Services.AddTransient(sp =>
            {
                var client = sp.GetService <IMongoClient>();
                return(client.GetDatabase(options.Database));
            });

            serviceCollection.Services.AddTransient <IMongoSessionFactory, MongoSessionFactory>();

            return(serviceCollection);
        }
Esempio n. 9
0
        public static IMergenBuilder ConfigureHandlers(this IMergenBuilder builder, Assembly assembly)
        {
            builder.Services.AddMediatR(Assembly.GetExecutingAssembly());

            if (assembly == null)
            {
                throw new ExecutionEngineException("dll type must be call");
            }

            //var classTypes = assembly.ExportedTypes.Select(t => t.GetTypeInfo()).Where(t => t.IsClass && !t.IsAbstract);

            //foreach (var type in classTypes)
            //{
            //    var interfaces = type.ImplementedInterfaces.Select(i => i.GetTypeInfo()).ToList();

            //    foreach (var handlerType in interfaces.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IRequestHandler<,>)))
            //    {
            //        builder.Services.AddTransient(handlerType.AsType(), type.AsType());
            //    }

            //    //foreach (var handlerType in interfaces.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAsyncRequestHandler<,>)))
            //    //{
            //    //    services.AddTransient(handlerType.AsType(), type.AsType());
            //    //}

            //    foreach (var handlerType in interfaces.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IRequestHandler<>)))
            //    {
            //        builder.Services.AddTransient(handlerType.AsType(), type.AsType());
            //    }

            //    //foreach (var handlerType in interfaces.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAsyncRequestHandler<>)))
            //    //{
            //    //    services.AddTransient(handlerType.AsType(), type.AsType());
            //    //}

            //    foreach (var handlerType in interfaces.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(INotificationHandler<>)))
            //    {
            //        builder.Services.AddTransient(handlerType.AsType(), type.AsType());
            //    }
            //}

            return(builder);
        }
Esempio n. 10
0
        public static IMergenBuilder AddMessageBox(this IMergenBuilder serviceCollection, string sectionName = SectionName)
        {
            if (string.IsNullOrWhiteSpace(sectionName))
            {
                sectionName = SectionName;
            }

            var configuration = serviceCollection.Services.BuildServiceProvider().GetService <IConfiguration>();

            var options = configuration.GetSection(sectionName).Get <MessageBoxOptions>();

            serviceCollection.Services.AddSingleton(options);
            serviceCollection.Services.AddMongoRepository <InboxMessage, string>();
            serviceCollection.Services.AddMongoRepository <OutboxMessage, string>();
            serviceCollection.AddInitializer <MessageBoxInitializer>();
            serviceCollection.Services.AddTransient <IMessageOutbox, MessageOutbox>();
            serviceCollection.Services.AddTransient <IMessageOutboxAccessor, MessageOutbox>();
            serviceCollection.Services.AddHostedService <OutboxHostedService>();
            serviceCollection.Services.AddTransient <IMessageInbox, MessageInbox>();

            return(serviceCollection);
        }
Esempio n. 11
0
 private static IMergenBuilder AddWebApiSwaggerDocs(this IMergenBuilder builder, Action <IMergenBuilder> registerSwagger)
 {
     registerSwagger(builder);
     builder.Services.AddSwaggerGen(c => c.DocumentFilter <WebApiDocumentFilter>());
     return(builder);
 }
Esempio n. 12
0
 public static IMergenBuilder AddWebApiSwaggerDocs(this IMergenBuilder builder, SwaggerOptions options)
 => builder.AddWebApiSwaggerDocs(b => b.AddSwaggerDocs(options));
Esempio n. 13
0
 public static IMergenBuilder AddWebApiSwaggerDocs(this IMergenBuilder builder,
                                                   Func <ISwaggerOptionsBuilder, ISwaggerOptionsBuilder> buildOptions)
 => builder.AddWebApiSwaggerDocs(b => b.AddSwaggerDocs(buildOptions));
Esempio n. 14
0
        public static IMergenBuilder AddBusRabbitMq(this IMergenBuilder serviceCollection, string sectionName         = SectionName,
                                                    Func <IRabbitMqPluginsRegistry, IRabbitMqPluginsRegistry> plugins = null,
                                                    Action <ConnectionFactory> connectionFactoryConfigurator          = null)
        {
            if (string.IsNullOrWhiteSpace(sectionName))
            {
                sectionName = SectionName;
            }

            var configuration = serviceCollection.Services.BuildServiceProvider().GetService <IConfiguration>();

            var options = configuration.GetSection(sectionName).Get <RabbitMqOptions>();

            serviceCollection.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 = serviceCollection.Services.BuildServiceProvider())
            {
                logger = serviceProvider.GetService <ILogger <IRabbitMqClient> >();
            }

            serviceCollection.Services.AddSingleton <IContextProvider, ContextProvider>();
            serviceCollection.Services.AddSingleton <ICorrelationContextAccessor>(new CorrelationContextAccessor());
            serviceCollection.Services.AddSingleton <IMessagePropertiesAccessor>(new MessagePropertiesAccessor());
            serviceCollection.Services.AddSingleton <IRabbitMqConventionsBuilder, RabbitMqConventionsBuilder>();
            serviceCollection.Services.AddSingleton <IConventionsProvider, RabbitMqConventionsProvider>();
            serviceCollection.Services.AddSingleton <IConventionsRegistry, ConventionsRegistry>();
            serviceCollection.Services.AddSingleton <IMessageSerializer, NewtonsoftJsonRabbitMqSerializer>();
            serviceCollection.Services.AddSingleton <IRabbitMqClient, RabbitMqClient>();
            serviceCollection.Services.AddSingleton <IBusPublisher, RabbitMqPublisher>();
            serviceCollection.Services.AddSingleton <IBusSubscriber, RabbitMqSubscriber>();
            serviceCollection.Services.AddTransient <RabbitMqExchangeInitializer>();
            serviceCollection.Services.AddHostedService <RabbitMqHostedService>();
            serviceCollection.AddInitializer <RabbitMqExchangeInitializer>();

            var pluginsRegistry = new RabbitMqPluginsRegistry();

            serviceCollection.Services.AddSingleton <IRabbitMqPluginsRegistryAccessor>(pluginsRegistry);
            serviceCollection.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)}'.");
            serviceCollection.Services.AddSingleton(connection);

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

            return(serviceCollection);
        }
Esempio n. 15
0
 public static IMergenBuilder AddDefaultBusPublisher(this IMergenBuilder collection)
 {
     collection.Services.AddSingleton <IBusPublisher, DefaultBusPublisher>();
     return(collection);
 }