Esempio n. 1
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddIdentityServer()
     .AddDeveloperSigningCredential()
     .AddInMemoryApiResources(Config.GetApiResource())
     .AddInMemoryIdentityResources(Config.GetIdentityResource())
     .AddInMemoryClients(Config.GetClients())
     .AddResourceOwnerValidator <ResourceOwnerPasswordValidator>()
     .AddProfileService <ProfileService>()
     .AddCorsPolicyService <CorsPolicyService>()
     ;
     services.AddScoped <IAccountService, AccountService>();
     //获取配置文件中的服务发现
     services.Configure <ServiceDiscoveryOptions>(Configuration.GetSection("ServiceDiscovery"));
     services.AddSingleton(sp =>
     {
         var logger             = sp.GetRequiredService <ILogger <ResilienceHttpClient> >();
         var httpContextAccesor = sp.GetRequiredService <IHttpContextAccessor>();
         int retryCount         = 3;
         var exceptionCountAllowBeforeBreaker = 3;
         var factory = new ResilienceClientFactory(logger, httpContextAccesor, retryCount, exceptionCountAllowBeforeBreaker);
         return(factory);
     });
     //注册全局单例IHttpClient
     services.AddSingleton <IHttpClient>(sp =>
     {
         return(sp.GetRequiredService <ResilienceClientFactory>().GetResilienceHttpClient());
     });
     services.AddMvc();
 }
Esempio n. 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //IdentityServer4
            services.AddTransient <IProfileService, ProfileService>();
            services.AddIdentityServer()
            .AddExtensionGrantValidator <SmsAuthCodeValidator>()
            .AddDeveloperSigningCredential()
            .AddInMemoryClients(Config.GetClients())
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddProfileService <ProfileService>();   //获取资源文件

            services.AddOptions();

            //consul服务
            services.Configure <ServiceDisvoveryOptions>(Configuration.GetSection("ServiceDiscovery"));
            services.AddSingleton <IDnsQuery>(p =>
            {
                var serviceConfiguration = p.GetRequiredService <IOptions <ServiceDisvoveryOptions> >().Value;

                return(new LookupClient(IPAddress.Parse(serviceConfiguration.Consul.DnsEndpoint.Address), serviceConfiguration.Consul.DnsEndpoint.Port));
            });

            //services.AddSingleton(new HttpClient());
            //注册全局单例ResilienceClientFactory
            services.AddSingleton <ResilienceClientFactory>(sp =>
            {
                var loggger                    = sp.GetRequiredService <ILogger <ResilienceClientFactory> >();
                var logggerHttpClinet          = sp.GetRequiredService <ILogger <ResilientHttpClient> >();
                var httpContextAccessor        = sp.GetRequiredService <IHttpContextAccessor>();
                var retryCount                 = 5;//重新发起多少次请求
                var expCountAllowedBeforeBreak = 5;
                var factory                    = new ResilienceClientFactory(loggger, httpContextAccessor, retryCount, expCountAllowedBeforeBreak, logggerHttpClinet);
                return(factory);
            });
            //注册全局单例IHttpClient
            services.AddSingleton <IHttpClient>(sp =>
            {
                var resilienceClientFactory = sp.GetRequiredService <ResilienceClientFactory>();
                return(resilienceClientFactory.GetResilientHttpClient());
            });

            services.AddScoped <IAuthCodeService, TestAuthCodeService>();
            services.AddScoped <IUserService, UserService>();

            services.AddMvc();
        }
Esempio n. 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
            .AddExtensionGrantValidator <SmsAuthCodeValidator>()   //把自定义的验证加进来
            .AddDeveloperSigningCredential()
            .AddInMemoryClients(Config.GetClients())
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources());

            services.AddOptions();
            services.Configure <ServiceDiscoveryOptions>(Configuration.GetSection("ServiceDiscovery"));//注册配置节
            services.AddSingleton <IDnsQuery>(p =>
            {
                var serviceConfiguration = p.GetRequiredService <IOptions <ServiceDiscoveryOptions> >().Value;

                return(new LookupClient(serviceConfiguration.Consul.DnsEndpoint.ToIPEndPoint()));//这里的地址是从配置文件中来的
            });

            //注册全局单例的ResilienceClientFactory
            services.AddSingleton(typeof(ResilienceClientFactory), sp => {
                var logger = sp.GetRequiredService <ILogger <ResilienceHttpClient> >();
                var httpcontextAccessor = sp.GetRequiredService <IHttpContextAccessor>();
                int retryCount          = 5;
                int exceptionCountAllowedBeforBreaking = 5;
                var factory = new ResilienceClientFactory(logger, httpcontextAccessor, retryCount, exceptionCountAllowedBeforBreaking);
                return(factory);
            });


            //services.AddSingleton(new HttpClient());//通过这种方式可以获取到单例的实例
            //获取全局单例HttpClient
            services.AddSingleton <IHttpClient>(sp => {
                return(sp.GetRequiredService <ResilienceClientFactory>().GetResilienceHttpClient());
            });

            services.AddScoped <IUserService, UserService>()
            .AddScoped <IAuthCodeService, TestAuthCodeService>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Esempio n. 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        { //.AddDeveloperSigningCredential()
            services.AddIdentityServer()
            .AddExtensionGrantValidator <Authentication.SmaAuthCodeValidaor>()
            .AddDeveloperSigningCredential()
            .AddInMemoryClients(Config.GetClients())
            .AddInMemoryIdentityResources(Config.GetIdentityResource())
            .AddInMemoryApiResources(Config.GetApiResource());

            services.AddTransient <IProfileService, ProfileService>();
            services.AddScoped <IAuthCodeService, TestAuthCodeService>()
            .AddScoped <IUserServices, UserService>();
            services.AddSingleton(new System.Net.Http.HttpClient());
            //获取配置文件中的服务发现
            services.Configure <ServiceDiscoveryOptions>(Configuration.GetSection("ServiceDiscovery"));
            services.AddSingleton <IDnsQuery>(p =>
            {
                var serviceConfigation = p.GetRequiredService <IOptions <ServiceDiscoveryOptions> >().Value;
                return(new LookupClient(serviceConfigation.Consul.DnsEndpoint.ToIPEndPoint()));
            });
            //注册全局唯一单例ResilienceClientFactory
            services.AddSingleton(typeof(ResilienceClientFactory), sp =>
            {
                var logger             = sp.GetRequiredService <ILogger <ResilienceHttpClient> >();
                var httpClinetAccessor = sp.GetRequiredService <IHttpContextAccessor>();
                var retryCount         = 3;
                var exceptionCountAllowBeforeBreaker = 3;
                var factory = new ResilienceClientFactory(logger, httpClinetAccessor, retryCount, exceptionCountAllowBeforeBreaker);
                return(factory);
            });
            //注册全局唯一单例IHttpClient;
            services.AddSingleton <IHttpClient>(sp =>
            {
                return(sp.GetRequiredService <ResilienceClientFactory>().GetResilienceHttpClient());
            });
            services.AddMvc();
        }
Esempio n. 5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
            .AddExtensionGrantValidator <SmsAuthCodeValidator>()
            .AddDeveloperSigningCredential()
            .AddInMemoryClients(Config.GetClients())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryIdentityResources(Config.GetIdentityResources());

            services.AddScoped <IUserService, UserService>();
            services.AddScoped <IAuthCodeService, TestAuthCodeService>();
            //services.AddScoped(typeof(HttpClient));
            //注册全局单例 ResilienceClientFactory
            services.AddSingleton(typeof(ResilienceClientFactory), sp =>
            {
                var logger = sp.GetRequiredService <ILogger <ResilientHttpClient> >();
                var httpcontextAccesser = sp.GetRequiredService <IHttpContextAccessor>();
                var retryCount          = 5;
                var exceptionCountAllowedBeforeBreaking = 5;
                var factory = new ResilienceClientFactory(logger, httpcontextAccesser, retryCount,
                                                          exceptionCountAllowedBeforeBreaking);
                return(factory);
            });

            //注册全局单例 httpclient
            services.AddSingleton <IHttpClient>(sp => sp.GetRequiredService <ResilienceClientFactory>().GetResilientHttpClient());
            services.Configure <Dtos.ServiceDisvoveryOptions>(Configuration.GetSection("ServiceDiscovery"));

            services.AddSingleton <IDnsQuery>(p =>
            {
                var serviceConfiguration = p.GetService <IOptions <ServiceDisvoveryOptions> >().Value;
                return(new LookupClient(serviceConfiguration.Consul.DnsEndpoint.ToIpEndPoint()));
            });
            services.AddTransient <IProfileService, ProfileService>();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Esempio n. 6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();
            services.Configure <AppSetting>(x =>
            {
                x.MongoDbConnectionString = Configuration["MongoDbConnectionString"].ToString();
                x.MongoDbDatabase         = Configuration["MongoDbDatabase"].ToString();
            });

            services.Configure <ServiceDisvoveryOptions>(Configuration.GetSection("ServiceDiscovery"));

            services.AddSingleton <IDnsQuery>(p =>
            {
                var serviceConfiguration = p.GetRequiredService <IOptions <ServiceDisvoveryOptions> >().Value;

                return(new LookupClient(IPAddress.Parse(serviceConfiguration.Consul.DnsEndpoint.Address), serviceConfiguration.Consul.DnsEndpoint.Port));
            });

            services.AddSingleton <IConsulClient>(p => new ConsulClient(cfg =>
            {
                var serviceConfiguration = p.GetRequiredService <IOptions <ServiceDisvoveryOptions> >().Value;

                if (!string.IsNullOrEmpty(serviceConfiguration.Consul.HttpEndpoint))
                {
                    // if not configured, the client will use the default value "127.0.0.1:8500"
                    cfg.Address = new Uri(serviceConfiguration.Consul.HttpEndpoint);
                }
            }));


            services.AddSingleton <ResilienceClientFactory>(sp =>
            {
                var loggger                    = sp.GetRequiredService <ILogger <ResilienceClientFactory> >();
                var logggerHttpClinet          = sp.GetRequiredService <ILogger <ResilientHttpClient> >();
                var httpContextAccessor        = sp.GetRequiredService <IHttpContextAccessor>();
                var retryCount                 = 5;
                var expCountAllowedBeforeBreak = 5;
                var factory                    = new ResilienceClientFactory(loggger, httpContextAccessor, retryCount, expCountAllowedBeforeBreak, logggerHttpClinet);
                return(factory);
            });

            services.AddSingleton <IHttpClient>(sp =>
            {
                var resilienceClientFactory = sp.GetRequiredService <ResilienceClientFactory>();
                return(resilienceClientFactory.GetResilientHttpClient());
            });

            services.AddSingleton <MongoContactDbContext>();

            services.AddScoped <IContactFriendRequestRepository, MongoContactFriendRequestRepository>();

            services.AddScoped <IContactRepository, MongoContactRepository>();

            services.AddScoped <IUserService, UserService>();

            services.AddLogging(x => x.AddConsole());

            services.AddCap(options =>
            {
                options.UseMySql(Configuration.GetConnectionString("UserMysqlLocal"));
                //options.UseRabbitMQ(Configuration.GetConnectionString("RabbitMq"));
                options.UseRabbitMQ("localhost");
                options.UseDashboard();
                options.UseDiscovery(d =>
                {
                    d.DiscoveryServerHostName = "localhost";
                    d.DiscoveryServerPort     = 8500;
                    d.CurrentNodeHostName     = "localhost";
                    d.CurrentNodePort         = 58564;
                    d.NodeId   = 2;
                    d.NodeName = "CAP No.2 Node Contact.API";
                });
            });

            services.AddMvc();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.Authority            = "http://localhost:4000";
                options.Audience             = "gateway_contactapi";
                options.RequireHttpsMetadata = false;
            });
        }
Esempio n. 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ReCommandDbContext>(builder =>
            {
                builder.UseMySQL(Configuration.GetConnectionString("UserMysqlLocal"), x =>
                {
                    x.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                });

                //builder.UseMySQL(Configuration.GetConnectionString("UserMysql"));
            });

            services.AddOptions();
            services.Configure <ServiceDisvoveryOptions>(Configuration.GetSection("ServiceDiscovery"));

            services.AddSingleton <IDnsQuery>(p =>
            {
                var serviceConfiguration = p.GetRequiredService <IOptions <ServiceDisvoveryOptions> >().Value;

                return(new LookupClient(IPAddress.Parse(serviceConfiguration.Consul.DnsEndpoint.Address), serviceConfiguration.Consul.DnsEndpoint.Port));
            });

            services.AddSingleton <IConsulClient>(p => new ConsulClient(cfg =>
            {
                var serviceConfiguration = p.GetRequiredService <IOptions <ServiceDisvoveryOptions> >().Value;

                if (!string.IsNullOrEmpty(serviceConfiguration.Consul.HttpEndpoint))
                {
                    // if not configured, the client will use the default value "127.0.0.1:8500"
                    cfg.Address = new Uri(serviceConfiguration.Consul.HttpEndpoint);
                }
            }));

            services.AddSingleton <ResilienceClientFactory>(sp =>
            {
                var loggger                    = sp.GetRequiredService <ILogger <ResilienceClientFactory> >();
                var logggerHttpClinet          = sp.GetRequiredService <ILogger <ResilientHttpClient> >();
                var httpContextAccessor        = sp.GetRequiredService <IHttpContextAccessor>();
                var retryCount                 = 5;
                var expCountAllowedBeforeBreak = 5;
                var factory                    = new ResilienceClientFactory(loggger, httpContextAccessor, retryCount, expCountAllowedBeforeBreak, logggerHttpClinet);
                return(factory);
            });

            services.AddSingleton <IHttpClient>(sp =>
            {
                var resilienceClientFactory = sp.GetRequiredService <ResilienceClientFactory>();
                return(resilienceClientFactory.GetResilientHttpClient());
            });


            services.AddScoped <IUserService, UserService>();
            services.AddScoped <IContactService, ContactService>();

            //services.AddTransient<ProjectCreatedIntergrationEventHandler>();



            services.AddMvc().AddJsonOptions(x =>
            {
                x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });


            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.Authority            = "http://localhost:4000";
                options.Audience             = "gateway_recommandapi";
                options.RequireHttpsMetadata = false;
            });

            services.AddCap(options =>
            {
                options.UseEntityFramework <ReCommandDbContext>();
                //options.UseRabbitMQ(Configuration.GetConnectionString("RabbitMq"));
                options.UseRabbitMQ("localhost");

                // 注册 Dashboard
                options.UseDashboard();

                // 注册节点到 Consul
                options.UseDiscovery(d =>
                {
                    d.DiscoveryServerHostName = "localhost";
                    d.DiscoveryServerPort     = 8500;
                    d.CurrentNodeHostName     = "localhost";
                    d.CurrentNodePort         = 58809;
                    d.NodeId   = 4;
                    d.NodeName = "CAP No.4 Node ReCommand.API";
                });
            });
        }
Esempio n. 8
0
        /// <summary>
        /// add service
        /// </summary>
        /// <param name="services"></param>
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // add handel exception
            services.AddMvc(options =>
            {
                //options.ModelBinderProviders.Insert(0, new EncryEntityBinderProvider());
                options.Filters.Add <ExceptionFilter>();
                options.Filters.Add <ActionFilter>();
                options.Filters.Add <ResourceFilter>();
                //options.Filters.Add<ModelValidFilter>();
            });
            //创建引擎单例
            EngineContext.Initialize(new GeneralEngine(services.BuildServiceProvider()));
            //注入接口
            services.AddAssembly("General.Api.Application");
            services.AddAssembly("General.Api.Core");
            //add 自定义验证策略
            //services.AddInnerAuthorize(Configuration);
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials()
                                  .Build());
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddFluentValidation(options =>
            {
                //add validator
                options.RegisterValidatorsFromAssembly(
                    RuntimeHelper.GetAssemblyByName("General.Api.Application"));
                options.RegisterValidatorsFromAssembly(
                    RuntimeHelper.GetAssemblyByName("General.Core"));
            });
            // override modelstate
            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = (context) =>
                {
                    var errors = context.ModelState
                                 .Values
                                 .SelectMany(x => x.Errors
                                             .Select(p => p.ErrorMessage))
                                 .ToList();

                    var result = new ValidatorResult()
                    {
                        Code    = 10009,
                        Success = false,
                        Message = "Validation errors",
                        Errors  = errors
                    };

                    return(new BadRequestObjectResult(result));
                };
            });
            //添加对AutoMapper的支持
            services.AddScoped <IMapper>(options =>
                                         MapperConfiguration.CreateMapper());
            //add swagger
            services.InitSwaggerGen(Configuration, Environment, AppContext.BaseDirectory);
            services.AddScopedExtension(Configuration);
            #region log
            //初始化logcontext
            services.InitLogContext();
            #endregion

            services.InitOtherContxt(Configuration, Environment, services.BuildServiceProvider());

            //注册全局单例 ResilienceClientFactory
            services.AddSingleton(typeof(ResilienceClientFactory), sp =>
            {
                var logger = sp.GetRequiredService <ILogger <ResilientHttpClient> >();
                var httpcontextAccesser = sp.GetRequiredService <IHttpContextAccessor>();
                var retryCount          = 5;
                var exceptionCountAllowedBeforeBreaking = 5;
                var factory = new ResilienceClientFactory(logger, httpcontextAccesser, retryCount,
                                                          exceptionCountAllowedBeforeBreaking, "general.api");
                return(factory);
            });
            //注册全局单例 httpclient
            services.AddSingleton <IHttpClient>(sp => sp.GetRequiredService <ResilienceClientFactory>().GetResilientHttpClient());
            //海康httpClient
            services.AddScoped(typeof(IHikVisionClient), typeof(HikVisionClient));
        }