public static void Register(IIocManager iocManager) { var services = new ServiceCollection(); IdentityRegistrar.Register(services); services.AddEntityFrameworkInMemoryDatabase(); var serviceProvider = WindsorRegistrationHelper.CreateServiceProvider(iocManager.IocContainer, services); var builder = new DbContextOptionsBuilder <InstaPoiskDbContext>(); builder.UseInMemoryDatabase(Guid.NewGuid().ToString()).UseInternalServiceProvider(serviceProvider); iocManager.IocContainer.Register( Component .For <DbContextOptions <InstaPoiskDbContext> >() .Instance(builder.Options) .LifestyleSingleton() ); }
private void SetupInMemoryDb() { var services = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase(); var serviceProvider = WindsorRegistrationHelper.CreateServiceProvider( IocManager.IocContainer, services ); var builder = new DbContextOptionsBuilder <SalesDbContext>(); builder.UseInMemoryDatabase("Test").UseInternalServiceProvider(serviceProvider); IocManager.IocContainer.Register( Component .For <DbContextOptions <SalesDbContext> >() .Instance(builder.Options) .LifestyleSingleton() ); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //注册Oracle数据库服务 services.AddOraDbContext(Configuration["DbConnString:OracleConn"]); //注册SqlServer数据库服务 //services.AddSqlDbContext(Configuration["DbConnString:SqlConn"]); //使用 WindsorContainer var windsorContainer = new WindsorContainer(); //注册模块 windsorContainer.Install(FromAssembly.Named("NemoStore.Repository")); windsorContainer.Install(FromAssembly.Named("NemoStore.Web")); //注册日志模块 windsorContainer.AddFacility <LoggingFacility>(facility => facility //.LogUsing(new Log4netFactory("log4net.config"))); .LogUsing <Log4netFactory>() //.UseLog4Net() .WithConfig("log4net.config")); ////var fStream = File.OpenRead(); //var kk = new Log4netFactory("log4net.config").Create("InfrastructureLog"); //kk.Debug("Info___________"); return(WindsorRegistrationHelper.CreateServiceProvider(windsorContainer, services)); }
public static void Register(IIocManager iocManager) { var services = new ServiceCollection(); WindsorRegistrationHelper.CreateServiceProvider(iocManager.IocContainer, services); var builder = new DbContextOptionsBuilder <TestDbContext>(); var inMemorySqlite = new SqliteConnection("Data Source=:memory:"); builder.UseSqlite(inMemorySqlite); iocManager.IocContainer.Register( Component .For <DbContextOptions <TestDbContext> >() .Instance(builder.Options) .LifestyleSingleton() ); inMemorySqlite.Open(); new TestDbContext(builder.Options).Database.EnsureCreated(); }
// 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 IServiceProvider ConfigureServices(IServiceCollection services) { services.AddDataProtection(); services.AddAuthorization(); services.AddWebEncoders(); services.AddDotVVM <DotvvmStartup>(); var connectionString = configuration.GetConnectionString("db"); services.AddDbContext <AppDbContext>(options => options.UseSqlServer(connectionString), ServiceLifetime.Transient); services.AddAutoMapper(typeof(CommonInstaller), typeof(DALInstaller), typeof(BLInstaller), typeof(WebInstaller)); new CommonInstaller().Install(services); new DALInstaller().Install(services); new BLInstaller().Install(services); new WebInstaller().Install(services); var container = new WindsorContainer(); container.AddFacility <TypedFactoryFacility>(); return(WindsorRegistrationHelper.CreateServiceProvider(container, services)); }
public override void PreInitialize() { Configuration.BackgroundJobs.IsJobExecutionEnabled = false; var services = new ServiceCollection(); services.AddAbpIdentity <Tenant, User, Role>(); services.AddIdentityServer() .AddDeveloperSigningCredential() .AddAbpPersistedGrants <SampleAppDbContext>() .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources()) .AddInMemoryApiResources(IdentityServerConfig.GetApiResources()) .AddInMemoryClients(IdentityServerConfig.GetClients()) .AddAbpIdentityServer <User>() .AddProfileService <AbpProfileService <User> >(); var serviceProvider = WindsorRegistrationHelper.CreateServiceProvider( IocManager.IocContainer, services ); }
public ServiceResolver(IServiceCollection services) { _container = new WindsorContainer(); _container.Kernel.ComponentRegistered += Kernel_ComponentRegistered; Assembly assemblyServices = typeof(IServiceDependency).Assembly; Assembly assemblyRepository = typeof(IRepositoryDependency).Assembly; _container.Register(Component.For <UoWInterceptor>()); _container.Register( //Component.For<UoWInterceptor>().LifeStyle.Transient, Classes.FromAssembly(assemblyServices).BasedOn(typeof(IServiceDependency)).WithService.AllInterfaces() .Configure(r => r.Interceptors <UoWInterceptor>()) , Classes.FromAssembly(assemblyRepository).BasedOn(typeof(IRepositoryDependency)).WithService.AllInterfaces() ); _serviceProvider = WindsorRegistrationHelper.CreateServiceProvider(_container, services); }
public static void Register(IIocManager iocManager) { var services = new ServiceCollection(); IdentityRegistrar.Register(services); services.AddEntityFrameworkInMemoryDatabase(); var serviceProvider = WindsorRegistrationHelper.CreateServiceProvider(iocManager.IocContainer, services); var builder = new DbContextOptionsBuilder <MindfightsDbContext>(); builder.UseInMemoryDatabase(Guid.NewGuid().ToString()).UseInternalServiceProvider(serviceProvider); iocManager.IocContainer.Register( Component .For <DbContextOptions <MindfightsDbContext> >() .Instance(builder.Options) .LifestyleSingleton() ); iocManager.Register(typeof(IPlayerService), typeof(Player), DependencyLifeStyle.Transient); iocManager.Register(typeof(ITeamService), typeof(Team), DependencyLifeStyle.Transient); iocManager.Register(typeof(IMindfightService), typeof(Mindfight), DependencyLifeStyle.Transient); iocManager.Register(typeof(IQuestionService), typeof(Question), DependencyLifeStyle.Transient); iocManager.Register(typeof(ITeamAnswerService), typeof(TeamAnswer), DependencyLifeStyle.Transient); iocManager.Register(typeof(IRegistrationService), typeof(Registration), DependencyLifeStyle.Transient); iocManager.Register(typeof(IResultService), typeof(Result), DependencyLifeStyle.Transient); iocManager.Register(typeof(ITourService), typeof(Tour), DependencyLifeStyle.Transient); iocManager.Register(typeof(IRepository <Models.City, long>), typeof(Models.City), DependencyLifeStyle.Transient); iocManager.Register(typeof(IRepository <Models.Team, long>), typeof(Models.Team), DependencyLifeStyle.Transient); iocManager.Register(typeof(IRepository <Models.Mindfight, long>), typeof(Models.Mindfight), DependencyLifeStyle.Transient); iocManager.Register(typeof(IRepository <Models.Question, long>), typeof(Models.Question), DependencyLifeStyle.Transient); iocManager.Register(typeof(IRepository <Models.TeamAnswer, long>), typeof(Models.TeamAnswer), DependencyLifeStyle.Transient); iocManager.Register(typeof(IRepository <Models.Registration, long>), typeof(Models.Registration), DependencyLifeStyle.Transient); iocManager.Register(typeof(IRepository <Models.MindfightResult, long>), typeof(Models.MindfightResult), DependencyLifeStyle.Transient); iocManager.Register(typeof(IRepository <Models.Tour, long>), typeof(Models.Tour), DependencyLifeStyle.Transient); }
protected EntityFrameworkCoreModuleTestBase() { var services = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase(); var serviceProvider = WindsorRegistrationHelper.CreateServiceProvider( LocalIocManager.IocContainer, services ); var builder = new DbContextOptionsBuilder <BloggingDbContext>(); builder.UseInMemoryDatabase() .UseInternalServiceProvider(serviceProvider); var options = builder.Options; LocalIocManager.IocContainer.Register( Component.For <DbContextOptions <BloggingDbContext> >().Instance(options).LifestyleSingleton() ); CreateInitialData(); }
public void Register(IIocManager iocManager) { var services = new ServiceCollection(); IdentityRegistrar.Register(services); services.AddEntityFrameworkSqlite(); var serviceProvider = WindsorRegistrationHelper.CreateServiceProvider(iocManager.IocContainer, services); // In-memory database only exists while the connection is open _connection = new SqliteConnection("DataSource=:memory:"); _connection.Open(); var builder = new DbContextOptionsBuilder <AcmStatisticsBackendDbContext>(); builder.UseSqlite(_connection).UseInternalServiceProvider(serviceProvider); iocManager.IocContainer.Register( Component .For <DbContextOptions <AcmStatisticsBackendDbContext> >() .Instance(builder.Options) .LifestyleSingleton()); }
public override void PreInitialize() { Configuration.UnitOfWork.IsTransactional = false; //EF Core InMemory DB does not support transactions var services = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase(); var serviceProvider = WindsorRegistrationHelper.CreateServiceProvider( IocManager.IocContainer, services ); var builder = new DbContextOptionsBuilder <BloggingDbContext>(); builder.UseInMemoryDatabase() .UseInternalServiceProvider(serviceProvider); IocManager.IocContainer.Register( Component .For <DbContextOptions <BloggingDbContext> >() .Instance(builder.Options) .LifestyleSingleton() ); }
public ServiceResolver(IServiceCollection services) { container = new WindsorContainer(); container.Register(Component.For <IUserProvider>().ImplementedBy <UserProvider>().LifestyleTransient()); container.Register(Component.For <IBookProvider>().ImplementedBy <BookProvider>().LifestyleTransient()); container.Register(Component.For <IClientProvider>().ImplementedBy <ClientProvider>().LifestyleTransient()); var mappingConfig = new MapperConfiguration(option => { option.AddProfile(new MappingProfile()); }); IMapper mapper = mappingConfig.CreateMapper(); container.Register(Component.For <IMapper>().LifestyleSingleton().UsingFactoryMethod(() => mapper)); serviceProvider = WindsorRegistrationHelper.CreateServiceProvider(container, services); ADD_INIT_VALUES_INTO_DB_TEMPORARY_FUNC( serviceProvider.GetService <SmartDbContext>(), serviceProvider.GetService <RoleManager <IdentityRole> >(), serviceProvider.GetService <UserManager <User> >()) .Wait(); }
// 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 IServiceProvider ConfigureServices(IServiceCollection services) { services.AddApplicationInsightsTelemetry(configuration); services.AddDataProtection(); services.AddAuthorization(); services.AddWebEncoders(); services.AddDotVVM <DotvvmStartup>(); services .AddAuthentication("Cookie") .AddCookie("Cookie", options => { options.LoginPath = new PathString("/"); options.Events = new CookieAuthenticationEvents { OnRedirectToReturnUrl = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri), OnRedirectToAccessDenied = c => DotvvmAuthenticationHelper.ApplyStatusCodeResponse(c.HttpContext, 403), OnRedirectToLogin = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri), OnRedirectToLogout = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri) }; }); services.AddMemoryCache(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.Configure <MiniProfilerOptions>(options => { options.RouteBasePath = "/profiler"; options.Storage = new MemoryCacheStorage(new MemoryCache(new MemoryCacheOptions()), TimeSpan.FromMinutes(60)); }); return(WindsorRegistrationHelper.CreateServiceProvider(InitializeWindsor(), services)); }
/// <summary> /// Register gear app /// </summary> /// <param name="services"></param> /// <param name="configAction"></param> /// <returns></returns> public static IServiceProvider RegisterGearWebApp(this IServiceCollection services, Action <GearServiceCollectionConfig> configAction) { var configuration = new GearServiceCollectionConfig { GearServices = services }; configAction(configuration); //Register system config services.RegisterSystemConfig(configuration.Configuration); services.Configure <FormOptions>(x => x.ValueCountLimit = configuration.ServerConfiguration.UploadMaximSize); //Global settings services.AddMvc(options => { options.EnableEndpointRouting = false; options.ModelBinderProviders.Insert(0, new GearDictionaryModelBinderProvider()); }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .AddJsonOptions(x => { x.SerializerSettings.DateFormatString = GearSettings.Date.DateFormat; }); services.AddGearSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddGearSingleton <IActionContextAccessor, ActionContextAccessor>(); services.AddUrlHelper(); //Register core razor services.RegisterCoreRazorModule(); //Use compression if (configuration.AddResponseCompression && configuration.HostingEnvironment.IsProduction()) { services.AddResponseCompression(); } services.AddHttpClient(); services.Configure <SecurityStampValidatorOptions>(options => { // enables immediate logout, after updating the user's stat. options.ValidationInterval = TimeSpan.Zero; }); //--------------------------------------Cors origin Module------------------------------------- if (configuration.UseDefaultCorsConfiguration) { services.AddOriginCorsModule(); } //---------------------------------Custom cache Module------------------------------------- if (configuration.CacheConfiguration.UseDistributedCache && configuration.CacheConfiguration.UseInMemoryCache) { throw new InvalidCacheConfigurationException("Both types of cached storage cannot be used"); } if (configuration.CacheConfiguration.UseDistributedCache) { services.AddDistributedMemoryCache() .AddCacheModule <DistributedCacheService, RedisConnection>(configuration.HostingEnvironment, configuration.Configuration); } else if (configuration.CacheConfiguration.UseInMemoryCache) { services.AddCacheModule <InMemoryCacheService, RedisConnection>(configuration.HostingEnvironment, configuration.Configuration); } //---------------------------------Api version Module------------------------------------- services.AddApiVersioning(options => { options.ReportApiVersions = configuration.ApiVersioningOptions.ReportApiVersions; options.AssumeDefaultVersionWhenUnspecified = configuration.ApiVersioningOptions.AssumeDefaultVersionWhenUnspecified; options.DefaultApiVersion = configuration.ApiVersioningOptions.DefaultApiVersion; options.ErrorResponses = configuration.ApiVersioningOptions.ErrorResponses; }); //--------------------------------------SignalR Module------------------------------------- if (configuration.SignlarConfiguration.UseDefaultConfiguration) { services.AddSignalRModule(); } //--------------------------------------Swagger Module------------------------------------- if (configuration.SwaggerServicesConfiguration.UseDefaultConfiguration) { services.AddSwaggerModule(configuration.Configuration); } //Register memory cache var cacheService = configuration.BuildGearServices.GetService <IMemoryCache>(); IoC.Container.Register(Component.For <IMemoryCache>().Instance(cacheService)); return(WindsorRegistrationHelper.CreateServiceProvider(IoC.Container, services)); }
public ServiceResolver(IServiceCollection services) { container = new WindsorContainer(); container.Register(Component.For <IServiceRepository>().ImplementedBy <ServiceRepository>()); serviceProvider = WindsorRegistrationHelper.CreateServiceProvider(container, services); }
/// <summary> /// Register gear app /// </summary> /// <param name="services"></param> /// <param name="hostingEnvironment"></param> /// <param name="configAction"></param> /// <param name="conf"></param> /// <returns></returns> public static IServiceProvider RegisterGearWebApp(this IServiceCollection services, IConfiguration conf, IHostingEnvironment hostingEnvironment, Action <GearServiceCollectionConfig> configAction) { IoC.Container.Register(Component.For <IConfiguration>().Instance(conf)); IoC.Container.Register(Component.For <IHostingEnvironment>().Instance(hostingEnvironment)); //----------------------------------------Health Check------------------------------------- services.AddHealthChecks(); services.AddDatabaseHealth(); //services.AddSeqHealth(); services.AddHealthChecksUI("health-gear-database", setup => { setup.SetEvaluationTimeInSeconds((int)TimeSpan.FromMinutes(2).TotalSeconds); setup.AddHealthCheckEndpoint(GearApplication.SystemConfig.MachineIdentifier, $"{GearApplication.SystemConfig.EntryUri}hc"); }); var configuration = new GearServiceCollectionConfig { GearServices = services, HostingEnvironment = hostingEnvironment, Configuration = conf }; configAction(configuration); //Register mappings from modules services.AddAutoMapper(configuration.GetAutoMapperProfilesFromAllAssemblies().ToArray()); //Register system config services.RegisterSystemConfig(configuration.Configuration); services.Configure <FormOptions>(x => x.ValueCountLimit = configuration.ServerConfiguration.UploadMaximSize); //Global settings services.AddMvc(options => { //Global options.EnableEndpointRouting = false; //Binders options.ModelBinderProviders.Insert(0, new GearDictionaryModelBinderProvider()); }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .AddJsonOptions(x => { x.SerializerSettings.DateFormatString = GearSettings.Date.DateFormat; }); services.AddGearSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddGearSingleton <IActionContextAccessor, ActionContextAccessor>(); services.AddUrlHelper(); //Use compression if (configuration.AddResponseCompression && configuration.HostingEnvironment.IsProduction()) { services.AddResponseCompression(); } services.AddHttpClient(); services.Configure <SecurityStampValidatorOptions>(options => { // enables immediate logout, after updating the user's stat. options.ValidationInterval = TimeSpan.Zero; }); //--------------------------------------Cors origin Module------------------------------------- if (configuration.UseDefaultCorsConfiguration) { services.AddOriginCorsModule(); } //---------------------------------Custom cache Module------------------------------------- if (configuration.CacheConfiguration.UseDistributedCache && configuration.CacheConfiguration.UseInMemoryCache) { throw new InvalidCacheConfigurationException("Both types of cached storage cannot be used"); } if (configuration.CacheConfiguration.UseDistributedCache) { services.AddDistributedMemoryCache() .AddCacheModule <DistributedCacheService>() .AddRedisCacheConfiguration <RedisConnection>(configuration.HostingEnvironment, configuration.Configuration); } else if (configuration.CacheConfiguration.UseInMemoryCache) { services.AddCacheModule <InMemoryCacheService>(); } //---------------------------------Api version Module------------------------------------- services.AddApiVersioning(options => { options.ReportApiVersions = configuration.ApiVersioningOptions.ReportApiVersions; options.AssumeDefaultVersionWhenUnspecified = configuration.ApiVersioningOptions.AssumeDefaultVersionWhenUnspecified; options.DefaultApiVersion = configuration.ApiVersioningOptions.DefaultApiVersion; options.ErrorResponses = configuration.ApiVersioningOptions.ErrorResponses; }); //--------------------------------------Swagger Module------------------------------------- if (configuration.SwaggerServicesConfiguration.UseDefaultConfiguration) { services.AddSwaggerModule(configuration.Configuration); } //Register memory cache IoC.Container.Register(Component .For <IMemoryCache>() .Instance(configuration.BuildGearServices.GetService <IMemoryCache>())); //Type Convertors TypeDescriptor.AddAttributes(typeof(DateTime), new TypeConverterAttribute(typeof(EuDateTimeConvertor))); return(WindsorRegistrationHelper.CreateServiceProvider(IoC.Container, services)); }
private static void ConfigureServices(HostBuilderContext context, IServiceCollection services) { Configuration cfg; if (Environment.GetEnvironmentVariable("RUNNING_IN_CONTAINER") != null) { cfg = new Configuration { RabbitMqBrokerName = Environment.GetEnvironmentVariable("RABBITMQ_BROKER_NAME"), RabbitMqQueueName = Environment.GetEnvironmentVariable("RABBITMQ_QUEUE_NAME"), RabbitMqHost = Environment.GetEnvironmentVariable("RABBITMQ_HOST"), RabbitMqUser = Environment.GetEnvironmentVariable("RABBITMQ_USER"), RabbitMqPassword = Environment.GetEnvironmentVariable("RABBITMQ_PASSWORD"), RabbitMqPrefetchCount = int.Parse(Environment.GetEnvironmentVariable("RABBITMQ_PREFETCH_COUNT"), CultureInfo.InvariantCulture), InfluxEndpoint = Environment.GetEnvironmentVariable("INFLUX_ENDPOINT"), InfluxUserName = Environment.GetEnvironmentVariable("INFLUX_USERNAME"), InfluxPassword = Environment.GetEnvironmentVariable("INFLUX_PASSWORD") }; } else { cfg = context.Configuration.GetSection("Configuration").Get <Configuration>(); } var container = new WindsorContainer(); container.AddFacility <TypedFactoryFacility>(); container.Install(new LogInstaller()); container.Register( Component.For <IIntegrationEventHandlerFactory>().AsFactory(new IntegrationEventHandlerComponentSelector()), Component.For <IEventBusSubscriptionsManager>() .ImplementedBy <InMemoryEventBusSubscriptionsManager>(), Component.For <IEventLogger>() .ImplementedBy <EventLogger>(), Component.For <IEventBus>() .ImplementedBy <EventBusRabbitMQ>() .DependsOn(new { brokerName = cfg.RabbitMqBrokerName, queueName = cfg.RabbitMqQueueName, prefetchCount = cfg.RabbitMqPrefetchCount }), Component.For <IRabbitMQPersistentConnection>() .ImplementedBy <DefaultRabbitMQPersistentConnection>() .DependsOn(new { hostName = cfg.RabbitMqHost, userName = cfg.RabbitMqUser, password = cfg.RabbitMqPassword }), Component.For <MachineDataIntegrationEventHandler>(), Component.For <IConfigureRepository, IWriteMachineDataRepository>() .ImplementedBy <MachineDataRepository>() .DependsOn(new { endpoint = cfg.InfluxEndpoint, userName = cfg.InfluxUserName, password = cfg.InfluxPassword }), Component.For <Service>()); WindsorRegistrationHelper.CreateServiceProvider(container, services); services.AddSingleton <IHostedService>(container.Resolve <Service>()); }
protected override IServiceProvider CreateServiceProvider(IServiceCollection serviceCollection) { return(WindsorRegistrationHelper.CreateServiceProvider(new WindsorContainer(), serviceCollection)); }
public static IServiceProvider UseWindsor(this IServiceCollection services) { var windsorContainer = new WindsorContainer(); return(WindsorRegistrationHelper.CreateServiceProvider(windsorContainer, services)); }
// 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 IServiceProvider ConfigureServices(IServiceCollection services) { services.AddOptions(); services.Configure <AppSettings>(Configuration.GetSection("AppSettings")); services.AddSingleton(Configuration); services.AddSingleton((IConfigurationRoot)Configuration); services.AddDataProtection(); services.AddAuthorization(); services.AddWebEncoders(); services.AddDotVVM(options => { options.AddDefaultTempStorages("Temp"); options.AddMiniProfilerEventTracing(); options.AddApplicationInsightsTracing(); var dynamicDataConfig = new AppDynamicDataConfiguration(); options.AddDynamicData(dynamicDataConfig); }); services.AddDbContext <AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity <AppUser, AppRole>() .AddEntityFrameworkStores <AppDbContext>() .AddDefaultTokenProviders(); services.Configure <IdentityOptions>(options => { // Password settings options.Password.RequireDigit = true; options.Password.RequiredLength = 8; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = true; options.Password.RequireLowercase = false; options.Password.RequiredUniqueChars = 6; // Lockout settings options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30); options.Lockout.MaxFailedAccessAttempts = 10; options.Lockout.AllowedForNewUsers = true; // User settings options.User.RequireUniqueEmail = true; }); services .AddAuthentication(AuthenticationConstants.AUTHENTICATION_TYPE_NAME) .AddCookie(AuthenticationConstants.AUTHENTICATION_TYPE_NAME, options => { // Cookie settings options.Cookie.HttpOnly = true; options.Cookie.Expiration = TimeSpan.FromDays(150); options.LoginPath = new PathString("/Default3"); // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login options.LogoutPath = "/Account/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied options.SlidingExpiration = true; options.Events = new CookieAuthenticationEvents { OnRedirectToReturnUrl = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri), OnRedirectToAccessDenied = c => DotvvmAuthenticationHelper.ApplyStatusCodeResponse(c.HttpContext, 403), OnRedirectToLogin = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri), OnRedirectToLogout = c => DotvvmAuthenticationHelper.ApplyRedirectResponse(c.HttpContext, c.RedirectUri) }; }); services.AddMemoryCache(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); return(WindsorRegistrationHelper.CreateServiceProvider(InitializeWindsor(), services)); }
public IServiceProvider CreateServiceProvider(IServiceCollection services) { return(WindsorRegistrationHelper.CreateServiceProvider(this, services)); }
public WindsorServiceResolver(IServiceCollection services, IWindsorContainer container) { _serviceProvider = WindsorRegistrationHelper.CreateServiceProvider(container, services); }
public virtual IServiceProvider ConfigureServices(IServiceCollection services) { return(WindsorRegistrationHelper.CreateServiceProvider(AbpBootstrapper.IocManager.IocContainer, services)); }
public IServiceProvider ConfigureServices(IServiceCollection services) { // Mvc services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddMvcOptions(mvc => { mvc.Filters.Add(new ValidationExceptionFilter()); }) .AddJsonOptions(options => { options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }); // Dbcontext & repo services.AddDbContext <DbContext, PmContext>(ctx => ctx.UseSqlServer(Configuration.GetConnectionString("Database"))); services.AddRepository(); services.AddSingleton <IDatabaseInformation, ConnectionStringDatabaseInformation>(); services.AddTransient <PmContext>(); services.Configure <IdentityOptions>(c => { // Password settings c.Password.RequireDigit = true; c.Password.RequiredLength = 8; c.Password.RequireNonAlphanumeric = false; c.Password.RequireUppercase = true; c.Password.RequireLowercase = false; c.Password.RequiredUniqueChars = 6; // Lockout settings c.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30); c.Lockout.MaxFailedAccessAttempts = 10; c.Lockout.AllowedForNewUsers = true; // User settings c.User.RequireUniqueEmail = true; }); services.AddTransient <UserManager <User> >(); // Authentication services.AddIdentity <User, IdentityRole>() .AddEntityFrameworkStores <PmContext>() .AddDefaultTokenProviders(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(c => { c.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Issuer"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) }; }); // Swagger services.AddHttpContextAccessor(); services.AddSwaggerGen(c => c.SwaggerDoc("v1", new Info { Title = "API", Version = "v1" })); services.ConfigureSwaggerGen(c => { c.CustomSchemaIds(x => x.FullName); c.AddSecurityDefinition("Bearer", new ApiKeyScheme() { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = "header", Type = "apiKey" }); c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > { { "Bearer", new string[] { } } }); }); // Httpclients services.AddHttpClient <IPhoneClient, MessageBirdClient>(c => { c.BaseAddress = new Uri("https://rest.messagebird.com/"); c.DefaultRequestHeaders.Add("Authorization", string.Format($"AccessKey {Configuration.GetSection("Messagebird:ApiKey").Value}")); }); var windsorContainer = WindsorContainerFactory.GetContainer(typeof(Startup).Assembly); var windsorServiceProvider = WindsorRegistrationHelper.CreateServiceProvider(windsorContainer, services); return(windsorServiceProvider); }
public static void AddCalendarServices(this IServiceCollection services, IConfiguration configuration) { // Infrastructure services.AddCors(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services .AddMiniProfiler(options => { options.RouteBasePath = "/profiler"; }) .AddEntityFramework(); // AWS services.AddSingleton <SecretManager>(); services.AddDefaultAWSOptions(configuration.GetAWSOptions()); services.AddAWSService <IAmazonSecretsManager>(); var sp = WindsorRegistrationHelper.CreateServiceProvider(_container, services); var sm = sp.GetService <SecretManager>(); // Authorization & Authentication services.AddAuthorization(auth => { auth.AddPolicy("JwtBearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser() .Build()); }); // var cognitoSettings = sm.GetCognitoOptions().Result; // // services // .AddAuthentication(opt => { opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; }) // .AddJwtBearer(opt => // { // opt.SaveToken = true; // opt.Audience = cognitoSettings.ClientId; // opt.Authority = $"https://cognito-idp.us-east-2.amazonaws.com/{cognitoSettings.UserPoolId}"; // opt.TokenValidationParameters = // JwtHelper.TokenValidationParameters(cognitoSettings.RSAModulus, cognitoSettings.RSAExponent, cognitoSettings.JwtIssuer); // // new TokenValidationParameters // // { // // RoleClaimType = "cognito:groups", // // }; // }); //services.AddAuthentication().AddJwtBearer( // (jwtBearerOptions) => { // jwtBearerOptions.TokenValidationParameters = JwtHelper.TokenValidationParameters( // cognitoSettings.RSAModulus, cognitoSettings.RSAExponent, cognitoSettings.JwtIssuer); // }); // Clients // services.AddSingleton(x => sm.GetCognitoOptions().Result); services.AddSingleton <CalendarFactory>(); // services.AddSingleton(x => x.GetService<CalendarFactory>().CreateCognitoClient()); // services.AddSingleton(x => x.GetService<CalendarFactory>().GetCognitoUserPool()); // Repositories & services //var cs = sm.GetConnectionString().Result; services.AddSingleton(typeof(IGenericRepository <>), typeof(GenericRepository <>)); services.AddSingleton(typeof(IUserOwnedGenericRepository <>), typeof(UserOwnedGenericRepository <>)); services.AddSingleton <IUserRepository, UserRepository>(); services.AddDbContext <CalendarDbContext>(); // GraphQL services.AddHttpContextAccessor(); services.AddSingleton <DocumentExecuter>(); services.AddSingleton(x => { var sp1 = WindsorRegistrationHelper.CreateServiceProvider(_container, services); return(x.GetService <CalendarFactory>().CreatePublicSchema(sp1)); }); // Auto registration services.Scan(scan => scan .FromAssemblies( Assembly.GetAssembly(typeof(CalendarFactory)), Assembly.GetAssembly(typeof(CalendarDbContext))) .AddClasses() .UsingRegistrationStrategy(RegistrationStrategy.Skip) .AsSelf() .WithSingletonLifetime()); // Tests AssertDiConfiguration(_container); }
public void AddAspnetCoreServices(IServiceCollection services) { _services = services; serviceProvider = WindsorRegistrationHelper.CreateServiceProvider(container, services); }
public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddSingleton(typeof(IConfiguration), Configuration); // ?? services .AddMvcCore(setup => { //while (setup.InputFormatters.Count > 0) // setup.InputFormatters.RemoveAt(0); //while (setup.OutputFormatters.Count > 0) // setup.OutputFormatters.RemoveAt(0); setup.InputFormatters.Insert(0, new JilInputFormatter()); setup.OutputFormatters.Insert(0, new JilOutputFormatter()); setup.Filters.Add(new CheckModelForNullAttribute(HostingEnvironment.IsDevelopment())); setup.Filters.Add(new ValidateModelAttribute(LoggerFactory, new JilSerializer(), HostingEnvironment.IsDevelopment())); setup.Filters.Add(new GlobalExceptionFilterAttribute(LoggerFactory, HostingEnvironment.IsDevelopment())); }) .AddApplicationPart(typeof(Controllers.Mp4Controller).Assembly) .AddControllersAsServices() //.AddJsonFormatters() .AddApiExplorer() .AddDataAnnotations(); services.AddMemoryCache(); services.AddSingleton <Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>(); var container = DIConfig.ConfigureWindsor(Configuration); services.AddRequestScopingMiddleware(container.BeginScope); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "eSyncTraining LTI MP4 API", Version = "v1" }); //c.DescribeAllParametersInCamelCase(); c.IgnoreObsoleteActions(); c.IgnoreObsoleteProperties(); //c.MapType<DateTime?>(() => // new Schema // { // Type = "integer", // Format = "int64", // Example = (long)DateTime.Now.ConvertToUnixTimestamp(), // Description = "MillisecondsSinceUnixEpoch", // //Default = (long)DateTime.Now.ConvertToUnixTimestamp(), // //Pattern = "pattern", // } //); //c.MapType<DateTime>(() => // new Schema // { // Type = "integer", // Format = "int64", // Example = (long)DateTime.Now.ConvertToUnixTimestamp(), // Description = "MillisecondsSinceUnixEpoch", // //Default = (long)DateTime.Now.ConvertToUnixTimestamp(), // //Pattern = "pattern", // } //); c.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "Authorization header using the Bearer scheme. " + "<br/> Example: \"Authorization: ltiapi {consumerKey};{courseId}\"" + "<br/> {courseId} - LMS course Id." + "For Sakai {courseId} - is GetHashCode() result for course context_id value.", Name = "Authorization", In = "header", Type = "apiKey" }); c.OperationFilter <FileUploadOperation>(); //Register File Upload Operation Filter }); services.AddOptions(); return(WindsorRegistrationHelper.CreateServiceProvider(container, services)); }
internal static IServiceProvider BuildWindsorCastleServiceProvider(this IServiceCollection serviceCollection) { var castleContainer = new WindsorContainer(); return(WindsorRegistrationHelper.CreateServiceProvider(castleContainer, serviceCollection)); }
public static void Register(IIocManager iocManager) { var services = new ServiceCollection(); WindsorRegistrationHelper.CreateServiceProvider(iocManager.IocContainer, services); }
public ServiceResolver(IServiceCollection services) { container = new WindsorContainer(); serviceProvider = WindsorRegistrationHelper.CreateServiceProvider(container, services); }