Ejemplo n.º 1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddCorsOption(this IServiceCollection services)
        {
            if (EasySharpServices.IsInitialized == false)
            {
                EasySharpServices.Services = services;
                EasySharpServices.Initialize();
            }

            Configuration = EasySharpServices.Builder();

            var options = new CorsOptions();

            Configuration.GetSection(nameof(CorsOptions)).Bind(options);

            //if Links=null, set links array to empty array
            var linksOption = options.Links ?? new string[] { };

            var policyName = options.Name;

            if (options.Enabled)
            {
                string[] clientUrls = linksOption.ToArray();

                services.AddCors(opt =>
                {
                    opt.AddPolicy(policyName,
                                  fbuilder => fbuilder.WithOrigins(clientUrls)
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
                });
            }

            return(services);
        }
Ejemplo n.º 2
0
        public static IServiceCollection AddCacheable(this IServiceCollection services)
        {
            if (EasySharpServices.IsInitialized == false)
            {
                EasySharpServices.Services = services;
                EasySharpServices.Initialize();
            }

            Configuration = EasySharpServices.Builder();

            var options = new Cacheable();

            Configuration.GetSection(nameof(Cacheable)).Bind(options);

            var redisOptions        = options.Redis ?? new RedisOptions();
            var localStorageOptions = options.LocalStorage ?? new LocalStorageOptions();

            if (redisOptions.Enable == true)
            {
                services.RedisCache(redisOptions);
            }

            if (localStorageOptions.Enable == true)
            {
                services.AddLocalStorage(Configuration);
            }

            return(services);
        }
Ejemplo n.º 3
0
        public static IApplicationBuilder UseDocs(this IApplicationBuilder app)
        {
            Configuration = EasySharpServices.Builder();

            var options = new SwaggerOptions();

            Configuration.GetSection(nameof(SwaggerOptions)).Bind(options);

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

            var routePrefix = string.IsNullOrWhiteSpace(options.RoutePrefix) ? "swagger" : options.RoutePrefix;

            app.UseStaticFiles()
            .UseSwagger(c => c.RouteTemplate = routePrefix + "/{documentName}/swagger.json");


            return(options.ReDocEnabled
                ? app.UseReDoc(c =>
            {
                c.RoutePrefix = routePrefix;

                if (options.SecurityOptions.Folder == "")
                {
                    c.SpecUrl = $"{options.Name}/swagger.json";
                }
                else
                {
                    c.SpecUrl = $"{options.SecurityOptions.Folder}/{options.Name}/swagger.json";
                }
            })
                : app.UseSwaggerUI(c =>
            {
                if (options.SecurityOptions.Folder == "")
                {
                    c.SwaggerEndpoint($"/{routePrefix}/{options.Name}/swagger.json", options.Title);
                }
                else
                {
                    c.SwaggerEndpoint($"/{options.SecurityOptions.Folder}/{routePrefix}/{options.Name}/swagger.json", options.Title);
                }

                c.RoutePrefix = routePrefix;

                c.EnableDeepLinking();

                // Additional OAuth settings
                c.OAuthClientId(options.SecurityOptions.ApiId);
                c.OAuthClientSecret(options.SecurityOptions.ClientSecret);
                c.OAuthAppName(options.Description);
                c.OAuthScopeSeparator(" ");
                c.OAuthUsePkce();
            }));
        }
Ejemplo n.º 4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseCorsOption(this IApplicationBuilder app)
        {
            Configuration = EasySharpServices.Builder();

            var options = new CorsOptions();

            Configuration.GetSection(nameof(CorsOptions)).Bind(options);

            if (options.Enabled)
            {
                app.UseCors(options.Name);
            }

            return(app);
        }
Ejemplo n.º 5
0
        public static IServiceCollection AddEfCore <TContext>(this IServiceCollection services)
            where TContext : DbContext
        {
            if (EasySharpServices.IsInitialized == false)
            {
                EasySharpServices.Services = services;
                EasySharpServices.Initialize();
            }

            Configuration = EasySharpServices.Builder();

            var option = new EfCoreOptions();

            Configuration.GetSection(nameof(EfCoreOptions)).Bind(option);

            services.AddDbContext <TContext>(
                options =>
                options.UseSqlServer(
                    option.ConnectionString
                    ));

            return(services);
        }
Ejemplo n.º 6
0
        public static IServiceCollection AddOutbox(this IServiceCollection services)
        {
            Configuration = EasySharpServices.Builder();

            var options = new OutboxOptions();

            Configuration.GetSection(nameof(OutboxOptions)).Bind(options);
            services.Configure <OutboxOptions>(Configuration.GetSection(nameof(OutboxOptions)));

            var dbContextOptions = new EfCoreOptions();

            Configuration.GetSection(nameof(EfCoreOptions)).Bind(dbContextOptions);

            if (options.Enable == false)
            {
                return(services);
            }

            switch (options.OutboxType.ToLowerInvariant())
            {
            case "efcore":
            case "ef":
                services.AddEfCoreOutboxStore(opts =>
                                              opts.UseSqlServer(
                                                  dbContextOptions.ConnectionString
                                                  ));
                break;

            default:
                throw new Exception($"Outbox type '{options.OutboxType}' is not supported");
            }

            services.AddScoped <IOutboxListener, OutboxListener>();
            services.AddHostedService <OutboxProcessor>();

            return(services);
        }
Ejemplo n.º 7
0
        public static IServiceCollection AddEventStore <TAggregate>(this IServiceCollection services) where TAggregate : IAggregate
        {
            Configuration = EasySharpServices.Builder();

            var options = new EventStoresOptions();

            Configuration.GetSection(nameof(EventStoresOptions)).Bind(options);
            services.Configure <EventStoresOptions>(Configuration.GetSection(nameof(EventStoresOptions)));

            var dbContextOptions = new EfCoreOptions();

            Configuration.GetSection(nameof(EfCoreOptions)).Bind(dbContextOptions);

            if (options.Enable == false)
            {
                return(services);
            }

            switch (options.EventStoreType.ToLowerInvariant())
            {
            case "efcore":
            case "ef":
                services.AddEfCoreEventStore(opts =>
                                             opts.UseSqlServer(
                                                 dbContextOptions.ConnectionString
                                                 ));
                break;

            default:
                throw new Exception($"Event store type '{options.EventStoreType}' is not supported");
            }

            services.AddScoped <IRepository <TAggregate>, Repository <TAggregate> >();
            services.AddScoped <IEventStore, EventStore>();

            return(services);
        }
Ejemplo n.º 8
0
        public static IServiceCollection AddEasySharp(this IServiceCollection services, params Type[] types)
        {
            var assemblies = types.Select(type => type.GetTypeInfo().Assembly);

            foreach (var assembly in assemblies)
            {
                services.AddMediatR(assembly);
            }

            services.AddScoped <ICommandBus, CommandBus>();
            services.AddScoped <IQueryBus, QueryBus>();
            services.AddScoped <IEventBus, EventBus>();

            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(ValidationBehavior <,>));

            EasySharpServices.Services = services;

            if (EasySharpServices.IsInitialized == false)
            {
                EasySharpServices.Initialize();
            }

            Configuration = EasySharpServices.Builder();

            services.AddOptions();

            services
            .AddMvc(opt => {
                opt.Filters.Add <ExceptionFilter>();
                opt.EnableEndpointRouting = false;
            })
            .AddNewtonsoftJson(jopt => jopt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore)
            .AddFluentValidation(cfg => { cfg.RegisterValidatorsFromAssemblies(assemblies); });


            return(services);
        }
        public static IServiceCollection AddMessageBroker(this IServiceCollection services)
        {
            Configuration = EasySharpServices.Builder();


            var options = new MessageBrokersOptions();

            Configuration.GetSection(nameof(MessageBrokersOptions)).Bind(options);
            services.Configure <MessageBrokersOptions>(Configuration.GetSection(nameof(MessageBrokersOptions)));

            if (options.Enable == false)
            {
                return(services);
            }

            switch (options.MessageBrokerType.ToLowerInvariant())
            {
            case "rabbitmq":
                return(services.AddRabbitMQ(Configuration));

            default:
                throw new Exception($"Message broker type '{options.MessageBrokerType}' is not supported");
            }
        }
Ejemplo n.º 10
0
        public static IServiceCollection AddDocs(this IServiceCollection services)
        {
            if (EasySharpServices.IsInitialized == false)
            {
                EasySharpServices.Services = services;
                EasySharpServices.Initialize();
            }

            Configuration = EasySharpServices.Builder();

            var options = new SwaggerOptions();

            Configuration.GetSection(nameof(SwaggerOptions)).Bind(options);

            var dt = _registry.TryAdd(RegistryName, true);

            if (!options.Enabled || !dt)
            {
                return(services);
            }

            services.AddSingleton(options);

            Uri termsOfService = new Uri(options.TermsOfService);
            Uri contactUrl     = new Uri(options.SecurityOptions.Contact.Url);
            Uri licenseUrl     = new Uri(options.SecurityOptions.License.Url);

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(options.Name, new OpenApiInfo
                {
                    Version        = options.Name,
                    Title          = options.Title,
                    Description    = options.Description,
                    TermsOfService = termsOfService,
                    Contact        = new OpenApiContact
                    {
                        Name  = options.SecurityOptions.Contact.Name,
                        Email = options.SecurityOptions.Contact.Email,
                        Url   = contactUrl,
                    },
                    License = new OpenApiLicense
                    {
                        Name = options.SecurityOptions.License.Name,
                        Url  = licenseUrl
                    }
                });

                c.CustomSchemaIds(type => type.ToString());

                if (options.SecurityOptions.XmlDoc)
                {
                    // curret project name not libraryName
                    var commentsFileName = $"{Assembly.GetEntryAssembly().GetName().Name}.XML";

                    var commentsFile = Path.Combine(System.AppContext.BaseDirectory, commentsFileName);

                    //FileHelpers.CreateFileIfDoesNotExist(commentsFile);

                    c.IncludeXmlComments(commentsFile);
                }

                if (options.IncludeSecurity)
                {
                    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                    {
                        Type  = SecuritySchemeType.OAuth2,
                        Flows = new OpenApiOAuthFlows
                        {
                            AuthorizationCode = new OpenApiOAuthFlow
                            {
                                AuthorizationUrl = new Uri(options.SecurityOptions.AuthorityURL),
                                TokenUrl         = new Uri(options.SecurityOptions.TokenUrl),
                                RefreshUrl       = new Uri(options.SecurityOptions.TokenUrl),
                                Scopes           = new Dictionary <string, string>
                                {
                                    { options.SecurityOptions.Scope.Name, options.SecurityOptions.Scope.Description },
                                }
                            }
                        }
                    });

                    c.OperationFilter <AuthorizeCheckOperationFilter>(options);
                }
            });

            if (options.IncludeSecurity)
            {
                services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
                .AddIdentityServerAuthentication(x =>
                {
                    x.Authority            = options.SecurityOptions.Authority;
                    x.ApiName              = options.SecurityOptions.ApiName;
                    x.SupportedTokens      = SupportedTokens.Both;
                    x.ApiSecret            = options.SecurityOptions.ClientSecret;
                    x.RequireHttpsMetadata = bool.Parse(options.SecurityOptions.RequireHttpsMetadata);

                    x.SaveToken     = true;
                    x.EnableCaching = true;
                    x.CacheDuration = TimeSpan.FromMinutes(10);
                });
            }

            return(services);
        }