예제 #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            var mapper = AutoMapperConfig.RegisterMappings().CreateMapper();

            services.AddSingleton(mapper);

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped <HttpContext>(p => p.GetService <IHttpContextAccessor>()?.HttpContext);

            IoCRegister.AddAutoMapperSetup(ref services);

            services.AddRegistration();
            services.AddHttpContextAccessor();
            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(FilterException));
                // Si hubiese Inyección de dependencias en el filtro
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2).
            AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
                          options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer           = false,
                ValidateAudience         = false,
                ValidateLifetime         = true,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["jwt:key"])),
                ClockSkew = TimeSpan.Zero
            });
        }
예제 #2
0
        /// <summary>
        /// Initialize all required interface
        /// </summary>
        /// <param name="container"></param>
        private static void RegisterAllDependencies(Container container)
        {
            container.Register(() => new EzCMSEntities(), Lifestyle.Scoped);
            container.Register <DbContext>(() => new EzCMSEntities(), Lifestyle.Scoped);

            container.Register(typeof(IRepository <>), typeof(Repository <>), Lifestyle.Scoped);
            container.Register(typeof(IHierarchyRepository <>), typeof(HierarchyRepository <>), Lifestyle.Scoped);

            IoCRegister.RegisterDepencies(container);

            // Logger using site settings
            container.Register(typeof(ILogger), () => new Logger(MethodBase.GetCurrentMethod().DeclaringType), Lifestyle.Scoped);

            #region Register controllers

            //container.RegisterMvcControllers(EzCMSUtilities.GetEzCMSAssemblies().ToArray());

            var registeredControllerTypes = SimpleInjectorMvcExtensions.GetControllerTypesToRegister(
                container, EzCMSUtilities.GetEzCMSAssemblies().ToArray());

            // Remove setup controller out of Register process
            registeredControllerTypes = registeredControllerTypes.Where(type => type.Name != "SetupController").ToArray();

            foreach (var controllerType in registeredControllerTypes)
            {
                RegisterController(container, controllerType);
            }

            #endregion
        }
예제 #3
0
파일: Startup.cs 프로젝트: hbravoal/TesoApp
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     IoCRegister.AddDbContext(services, Configuration.GetConnectionString("DefaultConnection"));
     IoCRegister.AddRepository(services);
     IoCRegister.AddServices(services);
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
 }
예제 #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient <ITeleSoftDBContext, TeleSoftDBContext>();
            services.AddDbContext <TeleSoftDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            IoCRegister.AddRegistration(services);
            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <TeleSoftDBContext>()
            .AddDefaultTokenProviders();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
                          options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer           = true,
                ValidateAudience         = true,
                ValidateLifetime         = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer      = "yourdomain.com",
                ValidAudience    = "yourdomain.com",
                IssuerSigningKey = new SymmetricSecurityKey(
                    Encoding.UTF8.GetBytes(Configuration["Llave_super_secreta"])),
                ClockSkew = TimeSpan.Zero
            });

            services.AddControllersWithViews();
            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
예제 #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Data Contexts
            services.AddScoped <ISecurityDbContext, SecurityDbContext>();
            services.AddDbContext <SecurityDbContext>(option => option.UseSqlServer(Configuration.GetConnectionString("CoreSecurityDB")));

            // MVC Version
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // Add Sessions
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            // Injection Dependences
            IoCRegister.AddRegistration(services);

            // Swagger
            SwaggerConfig.AddRegistration(services);

            // Enable Cors
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials()
                                  );
            });
        }
예제 #6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped <IManagementUserDBContext, ManagementUserDBContext>();
            services.AddDbContext <ManagementUserDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DataBaseConnection")));

            IoCRegister.AddRegistration(services);
            SwaggerConfig.AddRegistration(services);
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ProyectDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            IoCRegister.AddRegistration(services);
            SwaggerConfig.AddRegistration(services);
            //services.AddMvc();//Controllers();
            services.AddControllers();
        }
예제 #8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped <ICoworkingDBContext, CoworkingDBContext>();
            services.AddDbContext <CoworkingDBContext>(
                options => options.UseSqlServer(Configuration.GetConnectionString("DataBaseConnection")));

            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            IoCRegister.AddRegistration(services);
            SwaggerConfig.AddRegistration(services);
            services.AddControllers();
        }
예제 #9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddTransient<ICuentaRepository, CuentaRepository>();
            //services.AddTransient<ITransaccionRepository, TransaccionRepository>();
            services.AddDbContext <AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("con")));
            services.AddControllers().AddNewtonsoftJson();
            IoCRegister.AddRegistration(services);

            //se configura la app para la comunicacion con el front-end en Angular ya que el front pertenece a otro dominio
            services.AddCors(options => options.AddPolicy("AllowWebApp", builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
        }
예제 #10
0
 /// <summary>
 /// Configure.
 /// </summary>
 /// <param name="app">Aplicación.</param>
 /// <param name="env">Ambiente.</param>
 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
     _ = app.UseSwagger();
     _ = app.UseSwaggerUI(configuration =>
     {
         configuration.SwaggerEndpoint("../swagger/v1/swagger.json", GlobalResource.SwaggerTitle);
         configuration.RoutePrefix = "Documentation";
         configuration.DisplayRequestDuration();
     });
     IoCRegister.AddConfiguration(app, env);
 }
예제 #11
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddTransient <IPruebaTredaDBContext, PruebaTredaDBContext>();
     services.AddDbContext <PruebaTredaDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
     IoCRegister.AddRegistration(services);
     services.AddControllersWithViews();
     // In production, the Angular files will be served from this directory
     services.AddSpaStaticFiles(configuration =>
     {
         configuration.RootPath = "ClientApp/dist";
     });
 }
예제 #12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient <ICoworkingDBContext, CoworkingDBContext>();
            services.AddDbContext <CoworkingDBContext>(o => o.UseSqlServer(Configuration.GetConnectionString("DB")));
            IoCRegister.Register(services);

            SwaggerConfig.Register(services);

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            //agregar servicios
        }
예제 #13
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddScoped <IPosDBContext, PosDBContext>();
     services.AddDbContext <PosDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("POSConnDB")));
     IoCRegister.AddRegistration(services);
     services.AddControllers();
     //Allow Cors RG
     //https://www.youtube.com/watch?v=MBpH8sGqrMs
     services.AddCors(options => options.AddDefaultPolicy(
                          builder => builder.AllowAnyOrigin()
                          ));
 }
예제 #14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped <ICoworkingDataContext, CoworkingDataContext>();

            services.AddDbContext <CoworkingDataContext>(options => {
                //options.UseSqlServer(Configuration.GetConnectionString("DataBaseCoworking"));
                options.UseSqlite("Data Source=coworking.db");
            });

            IoCRegister.AddRegistration(services);
            SwaggerConfig.AddRegistration(services);

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped <ISolutionDBContext, SolutionDBContext>();
            services.AddDbContext <SolutionDBContext>(op => op.UseSqlServer(Configuration.GetConnectionString("DataBaseConnection")));

            IoCRegister.AddRegistration(services);

            services.AddControllersWithViews();
            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
예제 #16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "I'm Solver Documentation", Version = "v1"
                });
            });


            IoCRegister.AddRepository(services);
            IoCRegister.AddDbContext(services, this.Configuration.GetConnectionString("DefaultConnection"));
            IoCRegister.AddTransientServices(services);
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
예제 #17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped <IBibliotecaDBContext, BibliotecaDBContext>();
            services.AddDbContext <BibliotecaDBContext>(Options => Options.UseSqlServer(Configuration.GetConnectionString("DataBaseConnection")));
            IoCRegister.AddRegistration(services);
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddCors(options =>
            {
                options.AddPolicy("EnableCORS", builder =>
                {
                    builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials().Build();
                });
            });
        }
예제 #18
0
        /// <summary>
        /// ConfigureServices.
        /// </summary>
        /// <param name="services">Colección de servicios.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddNewtonsoftJson();
            services.AddSwaggerGen(configuration =>
            {
                ApplicationEnvironment appInfo = PlatformServices.Default.Application;
                List <string> xmlFiles         = Directory.GetFiles(appInfo.ApplicationBasePath, "*.xml", SearchOption.TopDirectoryOnly).ToList();
                xmlFiles.ForEach(xmlFile => configuration.IncludeXmlComments(xmlFile));
                configuration.SwaggerDoc("v1", new OpenApiInfo {
                    Title = GlobalResource.SwaggerTitle, Version = "v1"
                });
            });
            services.AddSwaggerGenNewtonsoftSupport();

            IoCRegister.AddRegistration(services);
        }
예제 #19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            // Inject Dependecies
            IoCRegister.AddRegistration(services);

            // JWT
            JwtAuthConfig.AddRegistration(services, this._configuration);

            // Cors
            CorsConfig.AddRegistration(services);

            //GraphQL
            GraphQLConfig.AddRegistration(services);
        }
예제 #20
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // Swagger
            SwaggerConfig.AddRegistration(services);

            // AutoMapper
            AutoMapperConfig.AddRegistration(services);

            // Inject Dependecies
            IoCRegister.AddRegistration(services);

            // JWT
            JwtAuthConfig.AddRegistration(services, _configuration);

            // Cors
            CorsConfig.AddRegistration(services);
        }
예제 #21
0
        public void ConfigureServices(IServiceCollection services)
        {
            //-------------- Configuration Database ----------------//

            services.AddDbContext <DataContext>(options =>
                                                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            //-------------- DATABASE ----------------//

            services.AddScoped <IDataContext, DataContext>();


            // -------REGISTER SERVICES ---------//

            IoCRegister.AddRegistration(services);


            services.AddControllersWithViews();
        }
예제 #22
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            services.AddTransient <IImagePickDbContext, ImagePickDbContext>();
            services.AddDbContext <ImagePickDbContext>(options =>
                                                       options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

            IdentityConfig.CreateIdentityIfNotCreated(services);

            AuthenticationConfig.ConfigureAuthenticationSettings(services, Configuration);

            IoCRegister.AddRegistration(services);

            SwaggerConfig.AddRegistration(services);

            services.AddControllers(options => options.RespectBrowserAcceptHeader = true)
            .AddNewtonsoftJson();
        }
예제 #23
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient <ICoworkingDBContext, CoworkingDBContext>();
            IoCRegister.AddRegistration(services);

            services.AddDbContext <CoworkingDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DataBaseConnection")));
            services.AddApplicationInsightsTelemetry(Configuration);

            SwaggerConfig.AddRegistration(services);

            services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = "https://coworkingidentity.azurewebsites.net/";
                options.RequireHttpsMetadata = false;
                options.ApiName = "api1";
            });

            services.AddMvc();
        }
예제 #24
0
        /// <summary>
        /// Register all IOC
        /// </summary>
        public static void RegisterIOC()
        {
            //Load project assemblies
            LoadProjectAssemblies();

            //Register IOC
            var container = new Container();

            container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
            container.Register(() => new EzCMSEntities(), Lifestyle.Singleton);
            container.Register <DbContext>(() => new EzCMSEntities(), Lifestyle.Singleton);

            container.Register(typeof(IRepository <>), typeof(Repository <>), Lifestyle.Singleton);
            container.Register(typeof(IHierarchyRepository <>), typeof(HierarchyRepository <>), Lifestyle.Singleton);
            IoCRegister.RegisterDepencies(container);

            // Logger using site settings
            container.Register(typeof(ILogger), () => new Logger(MethodBase.GetCurrentMethod().DeclaringType), Lifestyle.Scoped);
            HostContainer.SetContainer(container);
            container.Verify();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped <ISolutionDBContext, SolutionDBContext>();
            services.AddDbContext <SolutionDBContext>(op => op.UseSqlServer(Configuration.GetConnectionString("DataBaseConnection")));

            //services.AddCors(options =>
            //{
            //    options.AddPolicy("EnableCors",
            //    builder =>
            //    {
            //        builder
            //        //.WithOrigins("http://localhost:4200")
            //        .AllowAnyOrigin()
            //        .AllowAnyHeader()
            //        .AllowAnyMethod()
            //        .AllowCredentials()
            //        .Build();
            //    });
            //});
            services.AddCors(options =>
            {
                options.AddPolicy(name: MyPolicy,
                                  builder =>
                {
                    builder.WithOrigins("http://localhost:4200")
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowAnyOrigin();
                    //.WithHeaders(HeaderNames.ContentType, "x-custom-header")
                    //.WithMethods("PUT", "DELETE", "GET", "OPTIONS");
                });
            });


            IoCRegister.AddRegistration(services);
            services.AddControllers();
        }
예제 #26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <HNomiContext>(
                options => options.UseMySql("Server=localhost;Database=hnomi;User=davidrgh;Password=0000;",
                                            mySqlOptions =>
            {
                mySqlOptions.ServerVersion(new Version(5, 7, 17), ServerType.MySql);
            }
                                            ));

            services.AddCors(options =>
            {
                options.AddDefaultPolicy(
                    builder =>
                {
                    builder.WithOrigins("http://localhost:4200");
                });
            });

            IoCRegister.AddRegistration(services);
            SwaggerConfig.AddRegistration(services);

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
예제 #27
0
        public virtual void Start()
        {
            var serviceProvider = new ServiceCollection();

            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json");
            var config = builder.Build();

            serviceProvider.AddSingleton <IConfiguration>(context => config);

            var env = new SysHostEnvironment {
                EnvironmentName         = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"),
                ApplicationName         = AppDomain.CurrentDomain.FriendlyName,
                ContentRootPath         = AppDomain.CurrentDomain.BaseDirectory,
                ContentRootFileProvider = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory),
                WebRootPath             = AppDomain.CurrentDomain.BaseDirectory,
                WebRootFileProvider     = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory),
            };

            serviceProvider.AddSingleton(typeof(IWebHostEnvironment), env);

            var seqServer   = config.GetValue <string>("SeqServer");
            var levelSwitch = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information);

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.ControlledBy(levelSwitch)
                         .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                         .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                         .Enrich.FromLogContext()
                         .WriteTo.Seq(seqServer)
                         .WriteTo.Stackify(restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information)
                         .CreateLogger();
            serviceProvider.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));

            // asp.net
            serviceProvider.AddSingleton(PlatformServices.Default.Application);
            serviceProvider.AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>();
            serviceProvider.AddSingleton <DiagnosticSource>(new DiagnosticListener("Microsoft.AspNetCore"));
            serviceProvider.AddSingleton <DiagnosticListener>(new DiagnosticListener("Microsoft.AspNetCore"));
            serviceProvider.Configure <RazorViewEngineOptions>(options =>
            {
            });
            serviceProvider.AddRazorPages();
            serviceProvider.AddMvc();


            // cache
            serviceProvider.Configure <CacheOptions>(config.GetSection("Cache"));
            var cacheOptions = config.GetSection("Cache").Get <CacheOptions>();

            serviceProvider.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = cacheOptions.RedisConfiguration;
                options.InstanceName  = cacheOptions.RedisInstanceName;
            });
            serviceProvider.AddDistributedMemoryCache();


            //automapper
            serviceProvider.AddAutoMapper(typeof(BaseTest));
            MapperRegister.Register();


            var result = IoCRegister.Register(serviceProvider, config);

            Syinpo.Core.IoC.Init(result.Item1, result.Item2);
        }
예제 #28
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(c => c.EnableEndpointRouting = false);
            services.AddControllers(config =>
            {
                config.Filters.Add(typeof(CustomExceptionFilter));
                //config.Filters.Add( new CustomAuthorizeFilter( new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build() ) );
            })
            .AddNewtonsoftJson(
                //options =>
                //    options.SerializerSettings.ContractResolver =
                //        new CamelCasePropertyNamesContractResolver()
                )
            .AddControllersAsServices()
            .AddFluentValidation(cfg =>
            {
                cfg.ValidatorFactoryType = typeof(AttributedValidatorFactory);
                cfg.ImplicitlyValidateChildProperties = true;
            });
            services.AddOptions();


            services.AddHttpClient();
            services.AddHttpClient("monitor");
            services.AddHealthChecks().AddCheck <RandomHealthCheck>("random");


            // https
            var useHttps = Configuration.GetValue <bool?>("UseHttps");

            if (useHttps.HasValue && useHttps.Value)
            {
                services.AddHttpsRedirection(options =>
                {
                    options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
                    options.HttpsPort          = 443;
                });
            }

            // ef pro
            // HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize();

            // log
            var seqServer   = Configuration.GetValue <string>("SeqServer");
            var levelSwitch = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Warning);

            if (string.IsNullOrEmpty(seqServer))
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("DotNetCore.CAP", LogEventLevel.Error)
                             .MinimumLevel.Override("Microsoft.Extensions.Http", LogEventLevel.Warning)
                             .Enrich.FromLogContext()
                             .WriteTo.RollingFile(pathFormat: Path.Combine(AppContext.BaseDirectory, "logs\\log-{Date}.log"))
                             .CreateLogger();
            }
            else
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("DotNetCore.CAP", LogEventLevel.Error)
                             .MinimumLevel.Override("Microsoft.Extensions.Http", LogEventLevel.Warning)
                             .Enrich.FromLogContext()
                             .WriteTo.Seq(seqServer)
                             .CreateLogger();
            }
            services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));

            //automapper
            services.AddAutoMapper(typeof(Startup));
            MapperRegister.Register();

            // 跨域
            services.AddCors(o => o.AddPolicy("AllowAllPolicy", builder =>
            {
                builder
                .SetIsOriginAllowed(origin => true)
                .WithMethods("GET", "POST", "DELETE", "OPTIONS", "PUT")
                .AllowAnyHeader()
                .AllowCredentials();
            }));



            // 请求限制
            services.Configure <SysOptions>(Configuration.GetSection("Sys"));
            services.Configure <CacheOptions>(Configuration.GetSection("Cache"));
            services.AddHostedService <HealthCheckWorker>();



            // cache
            var cacheOptions = Configuration.GetSection("Cache").Get <CacheOptions>();

            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration        = cacheOptions.RedisConfiguration;
                options.InstanceName         = cacheOptions.RedisInstanceName;
                options.ConfigurationOptions = ConnectionOptions.Option;
            });
            services.AddDistributedMemoryCache();


            //signalr
            services.Configure <SqlBusOptions>(Configuration.GetSection("SqlBus"));
            var sqlBusOptions = Configuration.GetSection("SqlBus").Get <SqlBusOptions>();

            if (sqlBusOptions.UseSignalrRedis)
            {
                services.AddSignalR(p =>
                {
                    p.EnableDetailedErrors      = true;
                    p.ClientTimeoutInterval     = TimeSpan.FromSeconds(20);
                    p.HandshakeTimeout          = TimeSpan.FromSeconds(15);
                    p.KeepAliveInterval         = TimeSpan.FromSeconds(5);
                    p.MaximumReceiveMessageSize = null;
                })
                .AddJsonProtocol()
                .AddStackExchangeRedis(cacheOptions.RedisConfiguration, options =>
                {
                    options.Configuration.ChannelPrefix = "SigRis";
                });
            }
            else
            {
                services.AddSignalR(p =>
                {
                    p.EnableDetailedErrors      = true;
                    p.ClientTimeoutInterval     = TimeSpan.FromSeconds(20);
                    p.HandshakeTimeout          = TimeSpan.FromSeconds(15);
                    p.KeepAliveInterval         = TimeSpan.FromSeconds(5);
                    p.MaximumReceiveMessageSize = null;
                });
            }
            // signalrBus
            services.AddSignalrBusServer();


            // Monitor
            services.Configure <MonitorOptions>(Configuration.GetSection("Monitor"));
            var monitorOptions = Configuration.GetSection("Monitor").Get <MonitorOptions>();

            services.AddSingleton <MonitorExporter>();
            services.AddOpenTelemetry((sp, builder) =>
            {
                builder.SetSampler(new AlwaysSampleSampler());
                builder.UseMonitor(sp).AddRequestCollector().AddDependencyCollector();
            });
            services.AddScoped(resolver => resolver.GetService <TracerFactory>().GetTracer("syinpo-api-tracer"));
            if (monitorOptions.UseMonitor)
            {
                services.AddHostedService <MonitorWorker>();
            }


            // 服务总线
            services.Configure <CapBusOptions>(Configuration.GetSection("CapBus"));
            var capBusOptions = Configuration.GetSection("CapBus").Get <CapBusOptions>();

            services.AddCap(x =>
            {
                string capConnectionString = Configuration.GetConnectionString("CapConnection");
                x.UseSqlServer(capConnectionString);

                string rabbitmqConnectionString = capBusOptions.RabbitMQConnection;
                x.UseRabbitMQ(mq =>
                {
                    mq.UserName    = "******";
                    mq.Password    = "******";
                    mq.VirtualHost = "/";
                    mq.Port        = 5672;
                    mq.HostName    = rabbitmqConnectionString;
                });

                x.FailedRetryCount    = 2;
                x.FailedRetryInterval = 60 * 5;


                x.FailedThresholdCallback = (m) =>
                {
                    Log.Error($@"事件总线处理失败:A message of type {m.MessageType} failed after executing {x.FailedRetryCount} several times, requiring manual troubleshooting. Message name: {m.Message.GetName()}, id: {m.Message.GetId()}, value: {m.Message.Value.ToJson()}");
                };

                x.UseDashboard();

                x.Version = capBusOptions.VersionName;

                x.ConsumerThreadCount = 1;
            });

            // IoC & DI
            services.AddAutofac();
            var iocProvider = IoCRegister.Register(services, Configuration);

            IoC.Init(iocProvider.Item1, iocProvider.Item2);

            return(iocProvider.Item1);
        }
예제 #29
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     IoCRegister.AddRegistration(services, Configuration.GetConnectionString("DataBaseConnection"));
     SwaggerConfig.AddRegistration(services);
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
 }
예제 #30
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(c => c.EnableEndpointRouting = false);
            services.AddControllers(config =>
            {
                config.Filters.Add(typeof(CustomExceptionFilter));
                //config.Filters.Add( new CustomAuthorizeFilter( new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build() ) );
            })
            .AddNewtonsoftJson(
                //options =>
                //    options.SerializerSettings.ContractResolver =
                //        new CamelCasePropertyNamesContractResolver()
                )
            .AddControllersAsServices()
            .AddFluentValidation(cfg =>
            {
                cfg.ValidatorFactoryType = typeof(AttributedValidatorFactory);
                cfg.ImplicitlyValidateChildProperties = true;
            });
            services.AddOptions();


            services.AddHttpClient();
            services.AddHttpClient("monitor");
            services.AddHealthChecks().AddCheck <RandomHealthCheck>("random");


            // https
            var useHttps = Configuration.GetValue <bool?>("UseHttps");

            if (useHttps.HasValue && useHttps.Value)
            {
                services.AddHttpsRedirection(options =>
                {
                    options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
                    options.HttpsPort          = 443;
                });
            }

            // ef pro
            // HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize();

            // log
            var seqServer   = Configuration.GetValue <string>("SeqServer");
            var levelSwitch = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Warning);

            if (string.IsNullOrEmpty(seqServer))
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("DotNetCore.CAP", LogEventLevel.Error)
                             .MinimumLevel.Override("Microsoft.Extensions.Http", LogEventLevel.Warning)
                             .Enrich.FromLogContext()
                             .WriteTo.RollingFile(pathFormat: Path.Combine(AppContext.BaseDirectory, "logs\\log-{Date}.log"))
                             .CreateLogger();
            }
            else
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                             .MinimumLevel.Override("DotNetCore.CAP", LogEventLevel.Error)
                             .MinimumLevel.Override("Microsoft.Extensions.Http", LogEventLevel.Warning)
                             .Enrich.FromLogContext()
                             .WriteTo.Seq(seqServer)
                             .CreateLogger();
            }
            services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));

            //automapper
            services.AddAutoMapper(typeof(Startup));
            MapperRegister.Register();

            // 跨域
            services.AddCors(o => o.AddPolicy("AllowAllPolicy", builder =>
            {
                builder
                .SetIsOriginAllowed(origin => true)
                .WithMethods("GET", "POST", "DELETE", "OPTIONS", "PUT")
                .AllowAnyHeader()
                .AllowCredentials();
            }));

            // token
            RsaSecurityKey signingKey = CryptoHelper.CreateRsaSecurityKey();

            services.AddAuthentication();
            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters {
                    ValidateAudience         = false,
                    ValidateIssuer           = true,
                    ValidIssuer              = Configuration.GetValue <string>("IdentityServer"),
                    ValidateIssuerSigningKey = false,
                    IssuerSigningKey         = signingKey,
                    ValidateLifetime         = false
                };

                // WebSocket的Token来自QueryString
                options.Events = new JwtBearerEvents {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];
                        if (string.IsNullOrEmpty(accessToken))
                        {
                            context.Request.Query.TryGetValue("token", out accessToken);
                        }

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/hubs/")))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }

                        return(Task.CompletedTask);
                    }
                };
            });

            //.AddIdentityServerAuthentication( options =>
            //{
            //    options.Authority = Configuration.GetValue<string>( "IdentityServer" );
            //    options.RequireHttpsMetadata = false;// 指定是否为HTTPS

            //    options.ApiName = "api";

            //    // WebSocket的Token来自QueryString
            //    options.Events = new JwtBearerEvents {
            //        OnMessageReceived = context =>
            //        {
            //            var accessToken = context.Request.Query[ "access_token" ];
            //            if( string.IsNullOrEmpty( accessToken ) ) {
            //                context.Request.Query.TryGetValue( "token", out accessToken );
            //            }

            //            // If the request is for our hub...
            //            var path = context.HttpContext.Request.Path;
            //            if( !string.IsNullOrEmpty( accessToken ) && ( path.StartsWithSegments( "/hubs/" ) ) ) {
            //                // Read the token out of the query string
            //                context.Token = accessToken;
            //            }
            //            return Task.CompletedTask;
            //        }
            //    };
            //} );

            // permission
            services.AddAuthorization(options =>
            {
                options.AddPolicy("Permission", policyBuilder =>
                {
                    policyBuilder.Requirements.Add(new PermissionRequirement());
                    policyBuilder.RequireAuthenticatedUser();
                });
            });
            services.AddSingleton <IAuthorizationHandler, PermissionAuthorizationPolicy>();

            // api doc
            services.AddSwaggerGen(c =>
            {
                // https://localhost:44312/swagger/v1/swagger.json
                c.SwaggerDoc("v1",
                             new Microsoft.OpenApi.Models.OpenApiInfo {
                    Title       = "烽客 API",
                    Version     = "v1",
                    Description = "烽客 API 文档",
                });

                c.EnableAnnotations();

                //c.CustomOperationIds( e => $"{e.ActionDescriptor.RouteValues[ "action" ]}");
                c.CustomOperationIds(apiDesc =>
                {
                    return(apiDesc.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null);
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                if (File.Exists(xmlPath))
                {
                    c.IncludeXmlComments(xmlPath);
                }
                var xmlPath2 = Path.Combine(AppContext.BaseDirectory, "Syinpo.Model.xml");
                if (File.Exists(xmlPath2))
                {
                    c.IncludeXmlComments(xmlPath2);
                }

                //
                c.DescribeAllEnumsAsStrings();

                //
                //c.AddFluentValidationRules();

                //http://wmpratt.com/part-ii-swagger-and-asp-net-web-api-enabling-oauth2/
                c.OperationFilter <AuthorizeCheckOperationFilter>();

                //c.AddSecurityDefinition( "oauth2", new OAuth2Scheme {
                //    Type = "oauth2",
                //    Flow = "implicit",
                //    AuthorizationUrl = $"{Configuration.GetValue<string>( "IdentityServer" )}/connect/authorize",
                //    TokenUrl = $"{Configuration.GetValue<string>( "IdentityServer" )}/connect/token",
                //    Scopes = new Dictionary<string, string>()
                //    {
                //        { "api", "Syinpo API" }
                //    }
                //} );
            });

            // 请求限制
            services.Configure <SysOptions>(Configuration.GetSection("Sys"));
            services.Configure <CacheOptions>(Configuration.GetSection("Cache"));
            services.AddMemoryCache();
            //services.AddHostedService<CacheDamageWorker>();
            //services.AddHostedService<JieLongWorker>();
            services.AddHostedService <HealthCheckWorker>();


            // cache
            var cacheOptions = Configuration.GetSection("Cache").Get <CacheOptions>();

            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration        = cacheOptions.RedisConfiguration;
                options.InstanceName         = cacheOptions.RedisInstanceName;
                options.ConfigurationOptions = ConnectionOptions.Option;
            });
            services.AddDistributedMemoryCache();


            //signalr
            services.Configure <SqlBusOptions>(Configuration.GetSection("SqlBus"));
            var sqlBusOptions = Configuration.GetSection("SqlBus").Get <SqlBusOptions>();

            if (sqlBusOptions.UseSignalrRedis)
            {
                services.AddSignalR(p =>
                {
                    p.EnableDetailedErrors      = true;
                    p.ClientTimeoutInterval     = TimeSpan.FromSeconds(20);
                    p.HandshakeTimeout          = TimeSpan.FromSeconds(15);
                    p.KeepAliveInterval         = TimeSpan.FromSeconds(5);
                    p.MaximumReceiveMessageSize = null;
                })
                .AddJsonProtocol()
                .AddStackExchangeRedis(cacheOptions.RedisConfiguration, options =>
                {
                    options.Configuration.ChannelPrefix = "SigRis";
                });
            }
            else
            {
                services.AddSignalR(p =>
                {
                    p.EnableDetailedErrors      = true;
                    p.ClientTimeoutInterval     = TimeSpan.FromSeconds(20);
                    p.HandshakeTimeout          = TimeSpan.FromSeconds(15);
                    p.KeepAliveInterval         = TimeSpan.FromSeconds(5);
                    p.MaximumReceiveMessageSize = null;
                });
            }


            //signalrbus
            var sysOptions = Configuration.GetSection("Sys").Get <SysOptions>();

            if (sysOptions.SignalrBus.UserSignalrBus)
            {
                services.AddSignalrBus();
            }

            //hangfire
            services.Configure <HangfireOptions>(Configuration.GetSection("Hangfire"));
            var hangfireOptions = Configuration.GetSection("Hangfire").Get <HangfireOptions>();

            if (hangfireOptions.UseHangfire)
            {
                string taskConnectionString = Configuration.GetConnectionString("HangfireConnection");
                services.AddHangfire(x => x.UseSqlServerStorage(taskConnectionString));

                if (hangfireOptions.UseHangfireServer)
                {
                    services.AddHangfireServer();
                }

                JobStorage.Current = new SqlServerStorage(taskConnectionString);

                if (hangfireOptions.UseHangfireServer)
                {
                    HangfireRegister.Register();
                }
            }

            // Monitor
            services.Configure <MonitorOptions>(Configuration.GetSection("Monitor"));
            var monitorOptions = Configuration.GetSection("Monitor").Get <MonitorOptions>();

            services.AddSingleton <MonitorExporter>();
            services.AddOpenTelemetry((sp, builder) =>
            {
                builder.SetSampler(new AlwaysSampleSampler());
                builder.UseMonitor(sp).AddRequestCollector().AddDependencyCollector();
            });
            services.AddScoped(resolver => resolver.GetService <TracerFactory>().GetTracer("syinpo-api-tracer"));
            if (monitorOptions.UseMonitor)
            {
                services.AddHostedService <MonitorWorker>();
            }

            //数据保护
            services.AddDataProtection();
            services.Configure <PasswordHasherOptions>(option =>
            {
                option.CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2;
            });
            services.AddSingleton <Syinpo.Core.EasyLicense.PartnerAuthenticationHelper>();

            // 服务总线
            services.Configure <CapBusOptions>(Configuration.GetSection("CapBus"));
            var capBusOptions = Configuration.GetSection("CapBus").Get <CapBusOptions>();

            services.AddCap(x =>
            {
                string capConnectionString = Configuration.GetConnectionString("CapConnection");
                x.UseSqlServer(capConnectionString);

                string rabbitmqConnectionString = capBusOptions.RabbitMQConnection;
                x.UseRabbitMQ(mq =>
                {
                    mq.UserName    = "******";
                    mq.Password    = "******";
                    mq.VirtualHost = "/";
                    mq.Port        = 5672;
                    mq.HostName    = rabbitmqConnectionString;
                });

                x.FailedRetryCount    = 2;
                x.FailedRetryInterval = 60 * 5;


                x.FailedThresholdCallback = (m) =>
                {
                    Log.Error($@"事件总线处理失败:A message of type {m.MessageType} failed after executing {x.FailedRetryCount} several times, requiring manual troubleshooting. Message name: {m.Message.GetName()}, id: {m.Message.GetId()}, value: {m.Message.Value.ToJson()}");
                };

                x.UseDashboard();

                x.Version = capBusOptions.VersionName;

                x.ConsumerThreadCount = 1;
            });

            // IoC & DI
            services.AddAutofac();
            var iocProvider = IoCRegister.Register(services, Configuration);

            IoC.Init(iocProvider.Item1, iocProvider.Item2);

            // task
            if (hangfireOptions.UseHangfire)
            {
                GlobalConfiguration.Configuration.UseAutofacActivator(iocProvider.Item2, false);
            }

            //设置 Excel 帮助类为非商业版
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;



            return(iocProvider.Item1);
        }