Ejemplo n.º 1
0
 public override void ConfigureServices(CafConfigurationContext context)
 {
     AddAspNetServices(context.Services);
     context.ConfigFileOptions();
     AddAspNetCors(context);
     context.Services.AddObjectWrapper <IApplicationBuilder>();
 }
        public static void AddCafCors(this CafConfigurationContext context, Action <CafCorsOption> action)
        {
            CafCorsOption cafCorsOption = new CafCorsOption();

            action.Invoke(cafCorsOption);
            context.Services.AddObjectWrapper(cafCorsOption);
        }
Ejemplo n.º 3
0
 public override void ConfigureServices(CafConfigurationContext context)
 {
     context.Services.AddSingleton(typeof(IEFDbContextEntityMapping), typeof(EFDbContextEntityMapping));
     context.Services.AddScoped(typeof(IDbContextProvider <>), typeof(DbContextProvider <>));
     context.Services.AddScoped(typeof(ICafRepository <, >), typeof(CafEfCoreRepository <,>));
     context.Services.AddScoped(typeof(ICafRepository <>), typeof(CafEfCoreRepository <>));
 }
Ejemplo n.º 4
0
        public static void AddAuditing(this CafConfigurationContext context, Assembly assembly)
        {
            var option = context.Services.GetSingletonInstance <IObjectWrapper <CafAuditingOptions> >().Value;

            foreach (var map in option.AttributeLogMappings)
            {
                context.Services.AddSingleton(map.LogType);
                var handleType = typeof(IAuditingLogHandle <,>).MakeGenericType(map.LogType, map.AttributeType);
                var handleImp  = assembly.GetTypes().Where(o => o.IsClass && !o.IsAbstract && handleType.IsAssignableFrom(o)).FirstOrDefault();
                if (handleImp == null)
                {
                    throw new CafException($"未实现AuditingInfo的Handle实现{handleType.ToString()}");
                }
                context.Services.AddTransient(handleType, handleImp);


                var storeType = typeof(IAuditingStore <>).MakeGenericType(map.LogType);
                var storeImp  = assembly.GetTypes().Where(o => o.IsClass && !o.IsAbstract && storeType.IsAssignableFrom(o)).FirstOrDefault();
                if (storeImp == null)
                {
                    throw new CafException($"未实现AuditingInfo的Store实现{storeType.ToString()}");
                }
                context.Services.AddTransient(storeType, storeImp);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 添加跨域设置
        /// </summary>
        /// <param name="context"></param>
        private static void AddAspNetCors(CafConfigurationContext context)
        {
            var corsOption = context.Services.GetSingletonInstance <IObjectWrapper <CafCorsOption> >().Value;

            if (corsOption.Enable)
            {
                if (!string.IsNullOrEmpty(corsOption.ConfigurationSection))
                {
                    var corsFromAppsettings = context.Configuration["App:CorsOrigins"]
                                              ?.Split(",", StringSplitOptions.RemoveEmptyEntries)
                                              .Select(o => o.RemovePostFix("/"))
                                              .ToArray() ?? new string[] { };
                    corsOption.Origins.AddRange(corsFromAppsettings);
                }
                context.Services.AddCors(
                    options => options.AddPolicy(
                        _defaultCorsPolicyName,
                        builder => builder
                        .WithOrigins(
                            corsOption.Origins.Distinct().ToArray()
                            )
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials()));
            }
        }
Ejemplo n.º 6
0
        public static IGrpcServerConfiguration UseGrpcService(this CafConfigurationContext context, Action <IGrpcConfiguration> optionAction)
        {
            var config = context.Services.GetSingletonInstance <IGrpcServerConfiguration>();

            optionAction(config);
            return(config);
        }
Ejemplo n.º 7
0
        public override void ConfigureServices(CafConfigurationContext context)
        {
            JudgeConfigureConn(context);
            context.Services.AddSingleton(typeof(AppSettingsConfigure));
            context.Services.AddSingleton <IAppSettingsService, AppSettingsService>();

            context.Services.Configure <AccountOption>(context.Configuration.GetSection(
                                                           nameof(AccountOption)));
        }
Ejemplo n.º 8
0
        public override void ConfigureServices(CafConfigurationContext context)
        {
            var connectionString = "mongodb://49.234.12.187:27017";

            context.Services.AddMongoDbContext <ContentLibraryDbContext>(options =>
            {
                options.ConnectionString = connectionString;
                options.DatabaseName     = "UserBehavior";
            });
        }
Ejemplo n.º 9
0
 public override void BeforeConfigureServices(CafConfigurationContext context)
 {
     context.Services.AddSingleton <MongoDBContextSource>(new MongoDBContextSource());
     context.Services.TryAddTransient(
         typeof(IMongoDbContextProvider <>),
         typeof(MongoDbContextProvider <>)
         );
     context.Services.AddScoped(typeof(IMongoDbRepository <,>), typeof(MongoDbRepository <,>));
     context.Services.AddScoped(typeof(IMongoDbRepository <>), typeof(MongoDbRepository <>));
 }
Ejemplo n.º 10
0
 public override void BeforeConfigureServices(CafConfigurationContext context)
 {
     if (context.Services.GetSingletonInstanceOrNull <IGrpcServerConfiguration>() == null)
     {
         var grpcServerConfiguration = new GrpcServerConfiguration();
         var grpcClientConfiguration = new GrpcClientConfiguration();
         var grpcServiceProvider     = new GrpcServiceProvider(grpcServerConfiguration, grpcClientConfiguration);
         context.Services.AddSingleton <IGrpcServerConfiguration>(grpcServerConfiguration);
         context.Services.AddSingleton(typeof(IGrpcClientConfiguration), grpcClientConfiguration);
         context.Services.AddSingleton(typeof(IGrpcServiceProvider), grpcServiceProvider);
         context.Services.AddSingleton(typeof(IGrpcServiceGenerator), new GrpcServiceGenerator(grpcServiceProvider));
     }
 }
Ejemplo n.º 11
0
        public static AuthenticationBuilder AddCafJWTAuth(this CafConfigurationContext context, Action <CafJwtAuthConfiguration> action, string authenticationScheme, string defaultAuthenticateScheme = "", string defaultChallengeScheme = "", Func <MessageReceivedContext, Task> onMessageReceived = null)
        {
            CafJwtAuthConfiguration jWTAuthConfiguration = new CafJwtAuthConfiguration();

            action.Invoke(jWTAuthConfiguration);
            context.Services.AddSingleton(jWTAuthConfiguration);
            return(context.Services.AddAuthentication(options => {
                if (!string.IsNullOrEmpty(defaultAuthenticateScheme))
                {
                    options.DefaultAuthenticateScheme = defaultAuthenticateScheme;
                }
                if (!string.IsNullOrEmpty(defaultChallengeScheme))
                {
                    options.DefaultChallengeScheme = defaultChallengeScheme;
                }
            }).AddJwtBearer(authenticationScheme, options =>
            {
                options.Audience = jWTAuthConfiguration.Audience;

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // The signing key must match!
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = jWTAuthConfiguration.SymmetricSecurityKey,

                    // Validate the JWT Issuer (iss) claim
                    ValidateIssuer = true,
                    ValidIssuer = jWTAuthConfiguration.Issuer,

                    // Validate the JWT Audience (aud) claim
                    ValidateAudience = true,
                    ValidAudience = jWTAuthConfiguration.Audience,

                    // Validate the token expiry
                    ValidateLifetime = true,

                    // If you want to allow a certain amount of clock drift, set that here
                    ClockSkew = TimeSpan.Zero
                };

                if (onMessageReceived != null)
                {
                    options.Events = new JwtBearerEvents
                    {
                        OnMessageReceived = onMessageReceived
                    };
                }
            }));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 启用直连模式的 Grpc Client 客户端连接
        /// </summary>
        /// <param name="configs"></param>
        /// <param name="grpcNodes">Grpc 服务器节点列表</param>
        public static IGrpcClientConfiguration UseGrpcClientForDirectConnection(this CafConfigurationContext context, params GrpcServerNode[] grpcNodes)
        {
            var clientConfiguration = context.Services.GetSingletonInstance <IGrpcClientConfiguration>();
            var internalDict        = clientConfiguration.GrpcDirectConnectionConfiguration.GrpcServerNodes;

            foreach (var grpcNode in grpcNodes)
            {
                if (internalDict.ContainsKey(grpcNode.GrpcServiceName))
                {
                    throw new CafException("不能添加重复的名称的 Grpc 服务节点.");
                }

                internalDict.Add(grpcNode.GrpcServiceName, grpcNode);
            }
            return(clientConfiguration);
        }
Ejemplo n.º 13
0
        private SchedulerCenter GetScheduler(CafConfigurationContext context)
        {
            string dbProviderName = context.Configuration.GetSection("Quartz")["dbProviderName"];
            //string connectionString = context.Configuration.GetSection("Quartz")["connectionString"];

            var connectionString = context.Services.BuildServiceProvider().GetService <IOptions <Caf.Job.Entity.Quartz> >().Value.connectionString;

            if (string.IsNullOrWhiteSpace(connectionString))
            {
                connectionString = context.Configuration.GetSection("Quartz")["connectionString"];
            }

            string driverDelegateType = string.Empty;

            switch (dbProviderName)
            {
            case "SQLite-Microsoft":
            case "SQLite":
                driverDelegateType = typeof(SQLiteDelegate).AssemblyQualifiedName; break;

            case "MySql":
                driverDelegateType = typeof(MySQLDelegate).AssemblyQualifiedName; break;

            case "OracleODPManaged":
                driverDelegateType = typeof(OracleDelegate).AssemblyQualifiedName; break;

            case "SqlServer":
            case "SQLServerMOT":
                driverDelegateType = typeof(SqlServerDelegate).AssemblyQualifiedName; break;

            case "Npgsql":
                driverDelegateType = typeof(PostgreSQLDelegate).AssemblyQualifiedName; break;

            case "Firebird":
                driverDelegateType = typeof(FirebirdDelegate).AssemblyQualifiedName; break;

            default:
                throw new System.Exception("dbProviderName unreasonable");
            }
            JudgeConfigureConn(context);
            var             dbcontext       = context.Services.BuildServiceProvider().GetService <CafJobDbContext>();
            SchedulerCenter schedulerCenter = SchedulerCenter.Instance;

            schedulerCenter.Setting(new DbProvider(dbProviderName, connectionString), driverDelegateType, dbcontext);

            return(schedulerCenter);
        }
Ejemplo n.º 14
0
        public override void AfterConfigureServices(CafConfigurationContext context)
        {
            context.Services.AddSingleton <IGrpcConnectionUtility, GRpcConnectionUtility>();
            var         generator = context.Services.GetSingletonInstance <IGrpcServiceGenerator>();
            List <Type> types;
            List <Type> proxyTypes;

            generator.GeneraterClientProxyService(out types, out proxyTypes);
            foreach (var type in types)
            {
                var implType = proxyTypes.Find(o => type.IsAssignableFrom(o));
                if (implType != null)
                {
                    context.Services.AddSingleton(type, implType);
                }
            }
        }
Ejemplo n.º 15
0
 public override void BeforeConfigureServices(CafConfigurationContext context)
 {
     context.AddCafCors(o => { o.ConfigurationSection = "App:CorsOrigins"; o.Enable = true; });//添加跨域
     context.UseGrpcClientForDirectConnection(new[]
     {
         new GrpcServerNode
         {
             GrpcServiceIp   = "127.0.0.1",
             GrpcServiceName = "TestServiceName",
             GrpcServicePort = 8989
         }
     }).AddRpcClientAssembly(typeof(GrpcTestMoudle).Assembly);
     context.Services.AddHttpClient("webapi", c =>
     {
         c.BaseAddress = new Uri("http://localhost:44300/");
     });
     context.Services.AddControllers();
 }
Ejemplo n.º 16
0
        public void AddCaching(CafConfigurationContext context)
        {
            var sec = context.Configuration.GetSection(nameof(CacheOptions));

            context.Services.Configure <CacheOptions>(sec);

            var opt = sec.Get <CacheOptions>();

            if (opt.UseRedis)
            {
                context.Services.AddSingleton <ICafCache, CafRedisCache>();
            }
            else
            {
                context.Services.AddMemoryCache();
                context.Services.AddDistributedMemoryCache()
                .AddSingleton <ICafCache, CafMemoryCache>();
            }
        }
Ejemplo n.º 17
0
        private void JudgeConfigureConn(CafConfigurationContext context)
        {
            //notice:使用方需要指定配置AppSettingsConnection
            //string conn = context.Configuration.GetSection("ConnectionStrings")["AppSettingsConnection"];

            var conn = context.Services.BuildServiceProvider().GetService <IOptions <ConnectionStrings> >().Value.AppSettingsConnection;

            if (string.IsNullOrWhiteSpace(conn))
            {
                conn = context.Configuration.GetSection("ConnectionStrings")["AppSettingsConnection"];
            }
            try
            {
                context.Services.AddDbContext <CafAppsettingDbContext>(options => options.UseSqlServer(conn));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 18
0
        private void JudgeConfigureConn(CafConfigurationContext context)
        {
            //notice:使用方需要指定配置AppSettingsConnection
            //string conn = context.Configuration.GetSection("Quartz")["connectionString"];

            var conn = context.Services.BuildServiceProvider().GetService <IOptions <Caf.Job.Entity.Quartz> >().Value.connectionString;

            if (string.IsNullOrWhiteSpace(conn))
            {
                conn = context.Configuration.GetSection("Quartz")["connectionString"];
            }
            try
            {
                //var dboptions = new DbContextOptionsBuilder<CafAppsettingDbContext>().UseSqlServer(conn); ;
                //context.Services.AddScoped(s => new CafAppsettingDbContext(dboptions.Options));
                context.Services.AddDbContext <CafJobDbContext>(options => options.UseSqlServer(conn));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 19
0
        public override void BeforeConfigureServices(CafConfigurationContext context)
        {
            context.Services.AddSingleton <ITestNewService, TestNewService>();
            context.Services.AddSingleton <ITestService, TestService>();

            context.AddCafCors(o => { o.ConfigurationSection = "App:CorsOrigins"; o.Enable = true; });//添加跨域

            //context.UseGrpcService
            //    (
            //    o => {
            //        o.GrpcBindAddress = "0.0.0.0";
            //        o.GrpcBindPort = 8989;
            //    }).AddRpcServiceAssembly(typeof(sampleModule).Assembly);


            //添加JWT验证
            context.AddCafJWTAuth(o =>
            {
                o.Audience    = "caf";
                o.Expiration  = TimeSpan.FromDays(2);
                o.Issuer      = "caf";
                o.SecurityKey = "cafHKDH823J$5DSGS!@$g";
            });
        }
Ejemplo n.º 20
0
 public static void ConfigFileOptions(this CafConfigurationContext cafConfigurationContext)
 {
     cafConfigurationContext.Services.Configure <AWSS3Options>(cafConfigurationContext.Configuration.GetSection(nameof(AWSS3Options)));
 }
Ejemplo n.º 21
0
 public override void BeforeConfigureServices(CafConfigurationContext context)
 {
     context.Services.AddTransient <AuditingInterceptor>();
     context.Services.OnRegistred(AuditingInterceptorRegistrar.RegisterIfNeeded(context.Services));
 }
Ejemplo n.º 22
0
 public override void BeforeConfigureServices(CafConfigurationContext context)
 {
     context.AddCafCors(o => { o.ConfigurationSection = "App:CorsOrigins"; o.Enable = true; });//添加跨域
 }
Ejemplo n.º 23
0
        public override void ConfigureServices(CafConfigurationContext context)
        {
            context.Services.AddControllers().AddJsonOptions(options =>
            {
                //格式化日期时间格式

                //options.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter());
                //options.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverterNullable());
                //options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                //数据格式首字母小写
                options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                //数据格式原样输出
                //options.JsonSerializerOptions.PropertyNamingPolicy = null;
                //取消Unicode编码
                options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
                //忽略空值
                //options.JsonSerializerOptions.IgnoreNullValues = true;
                //允许额外符号
                options.JsonSerializerOptions.AllowTrailingCommas = true;
                //反序列化过程中属性名称是否使用不区分大小写的比较
                options.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
            }).AddControllersAsServices().AddMvcLocalization();

            #region swagger
            //context.Services.AddSwaggerGen(options =>
            //{
            //    options.SwaggerDoc("v1", new OpenApiInfo
            //    {
            //        Version = "v1",
            //        Title = "caf API",
            //        Description = "API for caf",
            //        Contact = new OpenApiContact() { Name = "Eddy", Email = "" }
            //    });
            //    options.DocInclusionPredicate((docName, description) => true);
            //    var security = new Dictionary<string, IEnumerable<string>>
            //        {
            //            {"Bearer", new string[] { }},
            //        };
            //    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
            //    {
            //        Description = "Please enter into field the word 'Bearer' followed by a space and the JWT value",
            //        Name = "Authorization",
            //        BearerFormat = "JWT",
            //        In = ParameterLocation.Header,
            //        Type = SecuritySchemeType.ApiKey,
            //        Scheme = "Bearer",

            //    });
            //    options.AddSecurityRequirement(new OpenApiSecurityRequirement
            //    {
            //        { new OpenApiSecurityScheme
            //        {
            //            Reference = new OpenApiReference()
            //            {
            //                Id = "Bearer",
            //                Type = ReferenceType.SecurityScheme
            //            }
            //        }, new string[] {} }
            //    });
            //    var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
            //    var xmlPath = Path.Combine(basePath, "caf.WebApi.xml");
            //    // var xmlPath1 = Path.Combine(basePath, "caf.Application.xml");
            //    var xmlPath2 = Path.Combine(basePath, "caf.Core.xml");
            //    //options.IncludeXmlComments(xmlPath);
            //    // options.IncludeXmlComments(xmlPath1);
            //    // options.IncludeXmlComments(xmlPath2);
            //});
            #endregion
        }
Ejemplo n.º 24
0
 public override void BeforeConfigureServices(CafConfigurationContext context)
 {
     //context.Services.AddObjectWrapper(new CafCorsOption());
 }
Ejemplo n.º 25
0
 public override void ConfigureServices(CafConfigurationContext context)
 {
 }
Ejemplo n.º 26
0
        public override void ConfigureServices(CafConfigurationContext context)
        {
            context.Services.AddOptions <AccountOptions>()
            .Configure <IAppSettingsService>(
                (o, s) =>
            {
                o.ResetPasswordCodeExpire = s.Get <int>("AccountOptions:ResetPasswordCodeExpire").Result;
                o.LockTime             = s.Get <int>("AccountOptions:LockTime").Result;
                o.PasswordErrTimeRange = s.Get <int>("AccountOptions:PasswordErrTimeRange").Result;
                o.MaxLoginErrCount     = s.Get <int>("AccountOptions:MaxLoginErrCount").Result;
                o.PasswordExpireDays   = s.Get <int>("AccountOptions:PasswordExpireDays").Result;
            });
            context.Services.AddControllers().AddJsonOptions(options =>
            {
                //格式化日期时间格式

                options.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter());
                options.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverterNullable());
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                //数据格式首字母小写
                options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                //数据格式原样输出
                //options.JsonSerializerOptions.PropertyNamingPolicy = null;
                //取消Unicode编码
                options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
                //忽略空值
                //options.JsonSerializerOptions.IgnoreNullValues = true;
                //允许额外符号
                options.JsonSerializerOptions.AllowTrailingCommas = true;
                //反序列化过程中属性名称是否使用不区分大小写的比较
                options.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
            }).AddControllersAsServices().AddMvcLocalization();

            context.Services.AddDynamicWebApi();

            context.Services.AddIntegrationEventBus(x =>
            {
                x.UseKafka("49.234.12.187:9092");
            });

            #region swagger
            context.Services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version     = "v1",
                    Title       = "caf API",
                    Description = "API for caf",
                    Contact     = new OpenApiContact()
                    {
                        Name = "Eddy", Email = ""
                    }
                });
                options.DocInclusionPredicate((docName, description) => true);
                var security = new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", new string[] { } },
                };
                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Description  = "Please enter into field the word 'Bearer' followed by a space and the JWT value",
                    Name         = "Authorization",
                    BearerFormat = "JWT",
                    In           = ParameterLocation.Header,
                    Type         = SecuritySchemeType.ApiKey,
                    Scheme       = "Bearer",
                });
                options.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    { new OpenApiSecurityScheme
                      {
                          Reference = new OpenApiReference()
                          {
                              Id   = "Bearer",
                              Type = ReferenceType.SecurityScheme
                          }
                      }, new string[] {} }
                });
                var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径)
                var xmlPath  = Path.Combine(basePath, "caf.WebApi.xml");
                // var xmlPath1 = Path.Combine(basePath, "caf.Application.xml");
                var xmlPath2 = Path.Combine(basePath, "caf.Core.xml");
                //options.IncludeXmlComments(xmlPath);
                // options.IncludeXmlComments(xmlPath1);
                // options.IncludeXmlComments(xmlPath2);
            });
            #endregion
        }
Ejemplo n.º 27
0
 public override void ConfigureServices(CafConfigurationContext context)
 {
     context.Services.AddSingleton(GetScheduler(context.Configuration));
 }
Ejemplo n.º 28
0
 public override void BeforeConfigureServices(CafConfigurationContext context)
 {
     context.Services.OnRegistred(UowRegistar.RegisterIfNeeded(context.Services));
 }
Ejemplo n.º 29
0
 public override void ConfigureServices(CafConfigurationContext context)
 {
     context.Services.AddObjectWrapper <IMapper>();
 }
Ejemplo n.º 30
0
 public override void AfterConfigureServices(CafConfigurationContext context)
 {
     context.Services.AddDynamicWebApi();
 }