// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddTransient(_ => new MySqlDatabase(Configuration["MySqlDatabase"])); services.AddTransient <IDonationManagerService, DonationManagerService>(); Log.Logger = new LoggerConfiguration() .Enrich.With(new LogEnricher()) .WriteTo.Console() .WriteTo.Seq(Configuration["seq"]) .CreateLogger(); Log.Information("DonationManager Starting!", Configuration.GetSection("Logging")); services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true)); services.AddMvc() .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { var problems = new CustomBadRequest(context); foreach (var error in problems?.Errors) { Log.Warning(error.Value[0]); } return(new BadRequestObjectResult(problems)); }; }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddMvc(); var connection = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext <DatabaseContext>(options => options.UseSqlite(connection)); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Device Management Api", Version = "v1" }); }); services.Configure <ApiBehaviorOptions>(a => { a.InvalidModelStateResponseFactory = context => { var problemDetails = new CustomBadRequest(context); return(new BadRequestObjectResult(problemDetails) { ContentTypes = { "application / json" } }); }; }); services.AddTransient <GlobalFacade>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <AppDbContext>(options => options.UseInMemoryDatabase("InMemoryDatabase")); services.AddScoped <IUserRepository, UserRepository>(); services.AddCors(); services.AddControllers(); services.AddAutoMapper(); var key = Encoding.ASCII.GetBytes(Settings.Secret); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true }; x.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Add("Token-Expired", "true"); } return(Task.CompletedTask); } }; }); services.AddMvc() .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { var problems = new CustomBadRequest(context); return(new BadRequestObjectResult(problems)); }; }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddNewtonsoftJson(options => { options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; options.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Include; options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize; options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Include; }); services.AddDbContext <PhonebookDbContext>(options => { options.UseNpgsql(Configuration.GetConnectionString("ConnectionDb")); }); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { var problems = new CustomBadRequest(context); return(new BadRequestObjectResult(problems)); }; }); services.AddMvcCore().AddDataAnnotations(); // Auto Mapper Configurations var mappingConfig = new MapperConfiguration(mc => { mc.AllowNullCollections = true; mc.AllowNullDestinationValues = true; mc.EnableNullPropagationForQueryMapping = true; mc.AddProfile(new AutoMapperProfile()); }); IMapper mapper = mappingConfig.CreateMapper(); services.AddSingleton(mapper); services.AddTransient(typeof(IPersonService), typeof(PersonService)); services.AddTransient(typeof(ICommunicationInfoService), typeof(CommunicationInfoService)); #region Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Phonebook Rest API Service", Version = "v1" }); c.SchemaFilter <EnumSchemaFilter>(); }); #endregion Swagger }
// 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_2) .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { var problems = new CustomBadRequest(context); return(new BadRequestObjectResult(problems)); }; }); }
// 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_2) // fluent validation .AddFluentValidation( fv => { fv.RegisterValidatorsFromAssemblyContaining <CreateCustomerCommandValidator>(); fv.ImplicitlyValidateChildProperties = true; }) // handle 404 error .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { var problems = new CustomBadRequest(context); return(new BadRequestObjectResult(problems)); }; options.ClientErrorMapping[404] = new ClientErrorData() { Link = "", Title = "Not found resources" }; }); // register auto mapper services.AddAutoMapper(new Assembly[] { typeof(AutoMapperProfile).GetTypeInfo().Assembly }); // register db context and migration assebly var connectionString = Configuration.GetConnectionString("CustomerContext").ToString(); services.AddDbContext <CustomerDatabaseContext> (options => options.UseSqlServer(connectionString, x => x.MigrationsAssembly("Accoon.Pitshop.CustomerApi.Persistence"))); services.AddTransient <IDatabaseContext, CustomerDatabaseContext>(); // register mediatr and command handlers services.AddMediatR(typeof(CreateCustomerHandler).GetTypeInfo().Assembly); // Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Accoon.Pitshop Customer Management API", Version = "v1" }); }); // health check services.AddHealthChecks() .AddSqlServer(connectionString); // sql server health check }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.Filters.Add <OperationCancelledExceptionFilter>(); options.Filters.Add <LoggingActionFilter>(); options.RespectBrowserAcceptHeader = true; // false by default options.OutputFormatters.Add(new XmlSerializerOutputFormatter()); }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { var Issues = new CustomBadRequest(context); return(new BadRequestObjectResult(Issues)); }; }); // api versioning services.AddApiVersioning(o => o.ApiVersionReader = new HeaderApiVersionReader("api-version")); services.AddHttpClient(Configuration); services.AddPollyServices(); services.ConfigureValues(Configuration); services.AddDBContext <ProductContext>(Configuration); services.AddTransient <TimingHandler>(); services.AddTransient <ValidateHeaderHandler>(); services.AddTransient <INoteRepository, NoteRepository>(); services.AddTransient <IProductRepository, ProductRepository>(); services.AddScoped <IEmployeeRepository, EmployeeRepository>(); services.AddScoped <ICustomterRepository, CustomerRepository>(); services.AddCors(policy => { policy.AddPolicy("CorsPolicy", options => options.AllowAnyHeader() .AllowAnyMethod() .AllowAnyOrigin()); }); services.AddLogging(configure => configure.AddConsole()); services.AddSingleton <LoggingActionFilter>(); }
// 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_2) .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { var problems = new CustomBadRequest(context); return(new BadRequestObjectResult(problems)); }; options.ClientErrorMapping[404] = new ClientErrorData() { Link = "", Title = "Not found resources" }; }); }
public void ConfigureServices(IServiceCollection services) { services.AddDbContext <AppDbContext>(options => { options.UseSqlServer(Configuration.GetConnectionString("Default")); }); //Making use of AutoMapper services.AddAutoMapper(typeof(Startup)); //Register services services.AddTransient <IUserRepository, UserRepository>(); //Add cors config which is a service extension services.ConfigureCors(); //Add accessor services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); //Add validation filter services.AddScoped <ValidationFilterAttribute>(); //Add logger config which is a service extension services.ConfigureLoggerService(); services.AddMvc(config => { // Content Negotiation goes here config.RespectBrowserAcceptHeader = true; }).ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { var problems = new CustomBadRequest(context); return(new BadRequestObjectResult(problems)); }; }).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) { // Add your AppInsights ID here to make it globally available // // services.AddApplicationInsightsTelemetry("9e5cc6db-d8d8-49c5-aa18-d60b4d06196b"); // Config data before config cookies so logged users can be checked on SqlServer services.Configure <Secrets.ConnectionStrings>(Configuration.GetSection("ConnectionStrings")); services.Configure <ApiBehaviorOptions>(a => { a.InvalidModelStateResponseFactory = context => { var problemDetails = new CustomBadRequest(context); return(new BadRequestObjectResult(problemDetails) { ContentTypes = { "application/problem+json", "application/problem+xml" } }); }; }); // data #region DataServices services.AddSingleton <IDataReport, DataReport>(); services.AddSingleton <ISendKey, Keys>(); services.AddSingleton <IQueue, Queue>(); services.AddSingleton <IEmail, Email>(); services.AddSingleton <IEmailMI4D, EmailMI4D>(); services.AddSingleton <MyIdentity>(); services.AddSingleton <IMyIdentity, MyIdentity>(); services.AddSingleton <StaticContent>(); services.AddSingleton <IImages, Images>(); services.AddSingleton <Questions>(); services.AddSingleton <ProfileName>(); services.AddSingleton <FeaturesDominant>(); services.AddSingleton <PersonalityForces>(); services.AddSingleton <YourMotivation>(); services.AddSingleton <FocusAttention>(); services.AddSingleton <LeaderDifferent>(); services.AddSingleton <ValuesDom>(); services.AddSingleton <EmotionalCompetent>(); services.AddSingleton <ComunicateMode>(); services.AddSingleton <InteractMode>(); services.AddSingleton <ProfileNames>(); services.AddSingleton <SaboteurSynteshis>(); services.AddSingleton <LimitedMatrix>(); services.AddSingleton <DifficultComunicate>(); services.AddSingleton <RelationshipDifficult>(); services.AddSingleton <FourLimited>(); services.AddSingleton <LimitedAttitude>(); services.AddSingleton <BehavioralAddiction>(); services.AddSingleton <EmotionalAddiction>(); services.AddSingleton <MentalAddiction>(); services.AddSingleton <DefenseMecanism>(); services.AddSingleton <NeuroticCompulsion>(); services.AddSingleton <CompetentMode>(); services.AddSingleton <SaboteurMode>(); services.AddSingleton <NameProfile>(); services.AddSingleton <LimitedForcesOne>(); services.AddSingleton <ProfileNameOne>(); services.AddSingleton <LimitedForcesTwo>(); services.AddSingleton <SaboteurNameOne>(); services.AddSingleton <LimitedForcesThree>(); services.AddSingleton <SaboteurNameTwo>(); services.AddSingleton <LimitedForcesFour>(); services.AddSingleton <ConflictsIdentified>(); services.AddSingleton <TriadHeHo>(); services.AddSingleton <SpecificsTriad>(); services.AddSingleton <NewObservation>(); services.AddSingleton <observationTriad>(); services.AddSingleton <FluxAnalyze>(); services.AddSingleton <DomProfile>(); services.AddSingleton <InternalPartners>(); services.AddSingleton <InternalPartOne>(); services.AddSingleton <InternalPartTwo>(); services.AddSingleton <ArchetypeDiscover>(); services.AddSingleton <EssentialCharacter>(); services.AddSingleton <DomProfileOne>(); services.AddSingleton <BigChallenge>(); services.AddSingleton <KeyWork>(); services.AddSingleton <IdealPart>(); services.AddSingleton <YourMoment>(); services.AddSingleton <ExistentialPain>(); services.AddSingleton <CristallyzationProcess>(); services.AddSingleton <BodyShape>(); services.AddSingleton <YourDevelopment>(); services.AddSingleton <BenefitsContact>(); services.AddSingleton <TwelveForces>(); services.AddSingleton <DyObservationOne>(); services.AddSingleton <DyObservationTwo>(); services.AddSingleton <DyObservationThree>(); services.AddSingleton <DyObservationFour>(); services.AddSingleton <DyObservationFive>(); services.AddSingleton <DyObservationSix>(); services.AddSingleton <DyObservationSeven>(); services.AddSingleton <DyObservationEight>(); services.AddSingleton <DyObservationNine>(); services.AddSingleton <DyObservationTen>(); services.AddSingleton <DyObservationEleven>(); services.AddSingleton <DyObservationTwelve>(); services.AddSingleton <DyObservationThirteen>(); services.AddSingleton <DyObservationFourteen>(); services.AddSingleton <DyObservationFifteen>(); services.AddSingleton <DyObservationSixteen>(); services.AddSingleton <DyObservationSeventeen>(); services.AddSingleton <DyObservationEighteen>(); services.AddSingleton <DyObservationNineteen>(); services.AddSingleton <DyObservationTwenty>(); services.AddSingleton <DyObservationTwentyOne>(); services.AddSingleton <DyObservationTwentyTwo>(); services.AddSingleton <DyObservationTwentyThree>(); services.AddSingleton <DyObservationTwentyFour>(); services.AddSingleton <DomProfileTwo>(); services.AddSingleton <PartnerOne>(); services.AddSingleton <PartnerTwo>(); services.AddSingleton <IdealPartner>(); services.AddSingleton <BehavioralResources>(); #endregion // storage services.AddSingleton <Blob>(); // add cors Bootstrap.ConfigCors(services, Configuration, HostEnvironment.IsDevelopment()); // DI config Bootstrap.DataProtection(services, Configuration); Bootstrap.ConsentCookie(services, Configuration, HostEnvironment.IsDevelopment()); Bootstrap.CookiesAuth(services, Configuration, HostEnvironment.IsDevelopment()); services .AddControllers() .AddNewtonsoftJson(options => { options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; options.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore; options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }) ; services.AddSwaggerDocument(options => { options.Title = "API for Profile4d"; options.Version = "1.21"; options.Description = "Made by www.ricardogaefke.com"; }); }
public void ConfigureServices(IServiceCollection services) { // register automapper services.AddAutoMapper(); // read pagination option data to class services.Configure <PaginationOption>(Configuration.GetSection("PaginationOption")); // pagination option filter services.AddTransient <PaginationOptionFilter>(); // register mvc services.AddMvc( ).SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { var problems = new CustomBadRequest(context); return(new BadRequestObjectResult(problems)); }; options.ClientErrorMapping[404] = new ClientErrorData() { Link = "", Title = "Not found resources" }; }); // swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); // register db context and migration assebly var connectionString = Configuration["ConnectionString"].ToString(); services.AddDbContext <AccoonDbContext> (options => options.UseSqlServer(connectionString, x => x.MigrationsAssembly("Accoon.Api.DataServices.Entities"))); // Register interfaces and classes // https://andrewlock.net/using-scrutor-to-automatically-register-your-services-with-the-asp-net-core-di-container/ // register base classes services.AddTransient <IService, ServiceBase>(); services.AddTransient(typeof(IRepository <, ,>), typeof(RepositoryBase <, ,>)); services.AddTransient(typeof(IUnitOfWork <>), typeof(UnitOfWork <>)); // register repositories services.Scan(scan => scan .FromAssembliesOf(typeof(AddressRepository)) .AddClasses(classes => classes.InExactNamespaceOf <AddressRepository>()) .AsImplementedInterfaces() .WithTransientLifetime()); // services services.Scan(scan => scan .FromAssembliesOf(typeof(AddressService)) .AddClasses(classes => classes.InNamespaceOf <AddressService>().Where(c => c.Name.EndsWith("Service"))) .AsImplementedInterfaces() .WithTransientLifetime()); // Health checkings // https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/implement-resilient-applications/monitor-app-health services.AddHealthChecks() .AddSqlServer(connectionString); // sql server health check // IHttpClientFactory // https://www.stevejgordon.co.uk/introduction-to-httpclientfactory-aspnetcore services.AddHttpClient <IGitHubClient, GithubClient>(client => { client.BaseAddress = new Uri("https://api.github.com/"); client.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json"); client.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactoryTesting"); }); // Mini Profiler // http://anthonygiretti.com/2018/12/16/common-features-in-asp-net-core-2-2-webapi-profiling/ // https://miniprofiler.com/dotnet/AspDotNetCore services.AddMiniProfiler(options => options.RouteBasePath = "/profiler" ).AddEntityFramework(); // Caching // http://anthonygiretti.com/2018/12/17/common-features-in-asp-net-core-2-2-webapi-caching/ // https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-2.2 // in mrmory cache services.AddMemoryCache(); // caching response for middlewares //services.AddResponseCaching(); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { // register repositories services.Scan(scan => scan .FromAssembliesOf(typeof(UserRepository)) .AddClasses(classes => classes.InExactNamespaceOf <UserRepository>()) .AsImplementedInterfaces() .WithTransientLifetime()); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2) // fluent validation .AddFluentValidation( fv => { fv.RegisterValidatorsFromAssemblyContaining <CreateCustomerCommandValidator>(); fv.ImplicitlyValidateChildProperties = true; }) // handle 404 error .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => { var problems = new CustomBadRequest(context); return(new BadRequestObjectResult(problems)); }; options.ClientErrorMapping[404] = new ClientErrorData() { Link = "", Title = "Not found resources" }; }); // register auto mapper services.AddAutoMapper(new Assembly[] { typeof(AutoMapperProfile).GetTypeInfo().Assembly }); // register db context and migration assebly var connectionString = Configuration.GetConnectionString("Context").ToString(); services.AddDbContext <DefaultDatabaseContext> (options => options.UseSqlServer(connectionString, x => x.MigrationsAssembly("Accoon.MMS.Api.Persistence"))); services.AddTransient <IDatabaseContext, DefaultDatabaseContext>(); // register mediatr and command handlers services.AddMediatR(typeof(CreateCustomerHandler).GetTypeInfo().Assembly); services.AddMediatR(typeof(LoginRequestHandler).GetTypeInfo().Assembly); services.AddMediatR(typeof(LoginResponseHandler).GetTypeInfo().Assembly); // health check services.AddHealthChecks() .AddSqlServer(connectionString); // sql server health check // idnetity framework services.AddDbContext <AppIdentityDbContext>(options => options.UseSqlServer(connectionString, b => b.MigrationsAssembly("Accoon.MMS.Api.Persistence"))); services.AddTransient <ITokenFactory, Accoon.MMS.Api.Infastructure.Auth.TokenFactory>(); services.AddTransient <IJwtFactory, Accoon.MMS.Api.Infastructure.Auth.JwtFactory>(); services.AddTransient <IJwtTokenHandler, Accoon.MMS.Api.Infastructure.Auth.JwtTokenHandler>(); services.AddTransient <IJwtTokenValidator, JwtTokenValidator>(); // Register the ConfigurationBuilder instance of AuthSettings var authSettings = Configuration.GetSection(nameof(AuthSettings)); services.Configure <AuthSettings>(authSettings); var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(authSettings[nameof(AuthSettings.SecretKey)])); // jwt wire up // Get options from app settings var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions)); // Configure JwtIssuerOptions services.Configure <JwtIssuerOptions>(options => { options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)]; options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)]; options.SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256); }); var tokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)], ValidateAudience = true, ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)], ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, RequireExpirationTime = false, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(configureOptions => { configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)]; configureOptions.TokenValidationParameters = tokenValidationParameters; configureOptions.SaveToken = true; configureOptions.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Add("Token-Expired", "true"); } return(Task.CompletedTask); } }; }); // api user claim policy services.AddAuthorization(options => { options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess)); }); // add identity var identityBuilder = services.AddIdentityCore <AppUser>(o => { // configure identity options o.Password.RequireDigit = false; o.Password.RequireLowercase = false; o.Password.RequireUppercase = false; o.Password.RequireNonAlphanumeric = false; o.Password.RequiredLength = 6; }); identityBuilder = new IdentityBuilder(identityBuilder.UserType, typeof(IdentityRole), identityBuilder.Services); identityBuilder.AddEntityFrameworkStores <AppIdentityDbContext>().AddDefaultTokenProviders(); // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "MMS web api", Version = "v1" }); c.AddSecurityDefinition("Bearer", new ApiKeyScheme { In = "header", Description = "Please insert JWT with Bearer into field", Name = "Authorization", Type = "apiKey" }); c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > { { "Bearer", new string[] { } } }); }); // Now register our services with Autofac container. var builder = new ContainerBuilder(); //builder.RegisterModule(new CoreModule()); //builder.RegisterModule(new InfrastructureModule()); // Presenters builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).Where(t => t.Name.EndsWith("Presenter")).SingleInstance(); builder.Populate(services); var container = builder.Build(); // Create the IServiceProvider based on the container. return(new AutofacServiceProvider(container)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //在startup中需要强制创建log4net var loggerFactory = LoggerFactory.Create(builder => { builder.AddLog4Net(); }); ILogger logger = loggerFactory.CreateLogger <Startup>(); var identityServer = ((ConfigurationSection)Configuration.GetSection("AppSetting:IdentityServerUrl")).Value; if (!string.IsNullOrEmpty(identityServer)) { services.AddAuthorization(); services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Authority = identityServer; options.RequireHttpsMetadata = false; // 指定是否为HTTPS options.Audience = "openauthapi"; }); } // 添加MiniProfiler服务 services.AddMiniProfiler(options => { // 设定访问分析结果URL的路由基地址 options.RouteBasePath = "/profiler"; options.ColorScheme = StackExchange.Profiling.ColorScheme.Auto; options.PopupRenderPosition = StackExchange.Profiling.RenderPosition.BottomLeft; options.PopupShowTimeWithChildren = true; options.PopupShowTrivial = true; options.SqlFormatter = new StackExchange.Profiling.SqlFormatters.InlineFormatter(); // options.IgnoredPaths.Add("/swagger/"); }).AddEntityFramework(); //显示SQL语句及耗时 //添加swagger services.AddSwaggerGen(option => { foreach (var controller in GetControllers()) { var groupname = GetSwaggerGroupName(controller); option.SwaggerDoc(groupname, new OpenApiInfo { Version = "v1", Title = groupname, Description = "by yubaolee" }); } logger.LogInformation($"api doc basepath:{AppContext.BaseDirectory}"); foreach (var name in Directory.GetFiles(AppContext.BaseDirectory, "*.*", SearchOption.AllDirectories).Where(f => Path.GetExtension(f).ToLower() == ".xml")) { option.IncludeXmlComments(name, includeControllerXmlComments: true); // logger.LogInformation($"find api file{name}"); } option.OperationFilter <GlobalHttpHeaderOperationFilter>(); // 添加httpHeader参数 if (!string.IsNullOrEmpty(identityServer)) { //接入identityserver option.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, Description = "OAuth2登陆授权", Flows = new OpenApiOAuthFlows { Implicit = new OpenApiOAuthFlow { AuthorizationUrl = new Uri($"{identityServer}/connect/authorize"), Scopes = new Dictionary <string, string> { { "openauthapi", "同意openauth.webapi 的访问权限" } //指定客户端请求的api作用域。 如果为空,则客户端无法访问 } } } }); option.OperationFilter <AuthResponsesOperationFilter>(); } }); services.Configure <AppSetting>(Configuration.GetSection("AppSetting")); services.AddControllers(option => { option.Filters.Add <OpenAuthFilter>(); }) .ConfigureApiBehaviorOptions(options => { // 禁用自动模态验证 // options.SuppressModelStateInvalidFilter = true; //启动WebAPI自动模态验证,处理返回值 options.InvalidModelStateResponseFactory = context => { var problems = new CustomBadRequest(context); return(new BadRequestObjectResult(problems)); }; }).AddNewtonsoftJson(options => { //忽略循环引用 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //不使用驼峰样式的key //options.SerializerSettings.ContractResolver = new DefaultContractResolver(); options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; }); services.AddMemoryCache(); services.AddCors(); // todo:如果正式 环境请用下面的方式限制随意访问跨域 // var origins = new [] // { // "http://localhost:1803", // "http://localhost:52789" // }; // if (Environment.IsProduction()) // { // origins = new [] // { // "http://demo.openauth.me:1803", // "http://demo.openauth.me:52789" // }; // } // services.AddCors(option=>option.AddPolicy("cors", policy => // policy.AllowAnyHeader().AllowAnyMethod().AllowCredentials().WithOrigins(origins))); //在startup里面只能通过这种方式获取到appsettings里面的值,不能用IOptions😰 var dbtypes = ((ConfigurationSection)Configuration.GetSection("AppSetting:DbTypes")).GetChildren() .ToDictionary(x => x.Key, x => x.Value); var connectionString = Configuration.GetConnectionString("OpenAuthDBContext"); logger.LogInformation($"系统配置的数据库类型:{JsonHelper.Instance.Serialize(dbtypes)},连接字符串:{connectionString}"); services.AddDbContext <OpenAuthDBContext>(); services.AddHttpClient(); services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(Configuration["DataProtection"])); //设置定时启动的任务 services.AddHostedService <QuartzService>(); }