public CoreServiceFixture() { var services = new ServiceCollection(); var serverVersion = new MariaDbServerVersion(new Version(10, 5, 4)); services.AddSingleton <IEntityInfo, EntityInfo>(); services.AddScoped(provider => { return(new Operater { Id = 1600000000000, Account = "alpha2008", Name = "余小猫" }); }); services.AddAdncInfraEfCoreMySql(options => { options.UseLowerCaseNamingConvention(); options.UseMySql(FixtureConsts.MySqlConnectString, serverVersion, optionsBuilder => { optionsBuilder.MinBatchSize(4) .CommandTimeout(10) .EnableRetryOnFailure() .UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery); }); options.LogTo(Console.WriteLine, LogLevel.Information); }); services.AddSingleton <ICapPublisher, NullCapPublisher>(); Container = services.BuildServiceProvider(); }
/// <summary> /// 注册EfcoreContext /// </summary> public virtual void AddEfCoreContext() { var mysqlConfig = _configuration.GetMysqlSection().Get <MysqlConfig>(); var serverVersion = new MariaDbServerVersion(new Version(10, 5, 4)); _services.AddDbContext <AdncDbContext>(options => { options.UseMySql(mysqlConfig.ConnectionString, serverVersion, optionsBuilder => { optionsBuilder.MinBatchSize(4); optionsBuilder.CommandTimeout(10); optionsBuilder.MigrationsAssembly(_serviceInfo.AssemblyName.Replace("WebApi", "Migrations")); optionsBuilder.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery); }); if (_environment.IsDevelopment()) { options.AddInterceptors(new DefaultDbCommandInterceptor()); options.EnableSensitiveDataLogging(); options.EnableDetailedErrors(); } //替换默认查询sql生成器,如果通过mycat中间件实现读写分离需要替换默认SQL工厂。 //options.ReplaceService<IQuerySqlGeneratorFactory, AdncMySqlQuerySqlGeneratorFactory>(); }); }
/// <summary> /// 注册EFCoreContext /// </summary> protected virtual void AddEfCoreContext() { var mysqlConfig = MysqlSection.Get <MysqlConfig>(); var serverVersion = new MariaDbServerVersion(new Version(10, 5, 4)); Services.AddAdncInfraEfCoreMySql(options => { options.UseLowerCaseNamingConvention(); options.UseMySql(mysqlConfig.ConnectionString, serverVersion, optionsBuilder => { optionsBuilder.MinBatchSize(4) .MigrationsAssembly(ServiceInfo.StartAssembly.GetName().Name.Replace("WebApi", "Migrations")) .UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery); }); if (this.IsDevelopment()) { //options.AddInterceptors(new DefaultDbCommandInterceptor()) options.LogTo(Console.WriteLine, LogLevel.Information) .EnableSensitiveDataLogging() .EnableDetailedErrors(); } //替换默认查询sql生成器,如果通过mycat中间件实现读写分离需要替换默认SQL工厂。 //options.ReplaceService<IQuerySqlGeneratorFactory, AdncMySqlQuerySqlGeneratorFactory>(); }); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { MariaDbServerVersion mariaDbServer = new MariaDbServerVersion(new Version(5, 5, 57)); optionsBuilder.UseMySql(ConnectionString, mariaDbServer); //optionsBuilder.UseSqlServer(ConnectionString); } }
public EfCoreDbcontextFixture() { var containerBuilder = new ContainerBuilder(); //内存数据库 //var option = new DbContextOptionsBuilder<MyDbContext>().UseInMemoryDatabase("My.D3").Options; //MyDbContext context = new MyDbContext(option); //InitializeDbForTests 初始化测试数据 //new TestDataBuilder(context).Build(); //注入 //Server.ContentRootPath = Path.GetFullPath(@"..\..\..\..\..\") + @"src\My.D3"; //IConfigurationRoot configuration = AppConfigurationHelper.Get(Server.ContentRootPath); //builder.RegisterType<SimpleDbContextProvider<MyDbContext>>().As<IDbContextProvider<MyDbContext>>().InstancePerLifetimeScope(); //var assemblysServices = Assembly.Load("My.D3.Application"); //builder.RegisterAssemblyTypes(assemblysServices).AsImplementedInterfaces(); //builder.RegisterAssemblyTypes(typeof(DbFixture).GetTypeInfo().Assembly); //var config = new MapperConfiguration(c => c.AddProfile(typeof(AdncProfile))); //IMapper mapper = config.CreateMapper(); //builder.RegisterInstance(mapper).As<IMapper>(); //var userContext = new UserContext() { ID = 1600000000000, Account = "alpha2008", Name = "余小猫" }; var dbstring = "Server=106.14.139.201;Port=13308;database=adnc_cus_dev;uid=root;pwd=alpha.netcore;"; //注册操作用户 containerBuilder.RegisterType <Operater>() .As <IOperater>() .InstancePerLifetimeScope(); //注册DbContext Options var serverVersion = new MariaDbServerVersion(new Version(10, 5, 4)); containerBuilder.Register <DbContextOptions>(c => { return(new DbContextOptionsBuilder <AdncDbContext>() .UseLoggerFactory(LoggerFactory.Create(builder => builder.AddDebug())) .UseMySql(dbstring, serverVersion, mySqlOptions => { mySqlOptions.MinBatchSize(4); }) .Options); }).InstancePerLifetimeScope(); //注册EntityInfo containerBuilder.RegisterType <EntityInfo>() .As <IEntityInfo>() .InstancePerLifetimeScope(); //注册DbContext2 containerBuilder.RegisterType <AdncDbContext>() .InstancePerLifetimeScope(); //注册Adnc.Infra.EfCore AdncInfraEfCoreModule.Register(containerBuilder); Container = containerBuilder.Build(); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //var connectionString = $"server={settings.Value.Address};port=3306;user={settings.Value.User};password={settings.Value.Password};database={settings.Value.Database_Name}"; optionsBuilder.UseMySql( settings.Value.ConnectionString, MariaDbServerVersion.FromString("10.4.12-MariaDB-1:10.4.12+maria~bionic"), MysqlOptions) .EnableSensitiveDataLogging() .EnableDetailedErrors(); }
public static NuGetApiOptions AddMariaDb(this NuGetApiOptions options) { options.Services.AddNuGetApiOptions <MySqlDatabaseOptions>(nameof(PackageFeedOptions.Database)); options.Services.AddNuGetFeedDbContextProvider <MySqlContext>("MariaDb", (provider, builder) => { var databaseOptions = provider.GetRequiredService <IOptionsSnapshot <MySqlDatabaseOptions> >(); var version = new MariaDbServerVersion(databaseOptions.Value.Version); builder.UseMySql(databaseOptions.Value.ConnectionString, version); }); return(options); }
public void Configure(IServiceCollection services) { var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .Build(); var databaseServerVersion = new MariaDbServerVersion("10.5"); services.AddSingleton(configuration) .AddSystemsInAssembly() .AddDbContextPool <GamemodeContext>(options => options.UseMySql(configuration.GetConnectionString("Default"), databaseServerVersion)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { string connectionString = Environment.GetEnvironmentVariable("MARIA_CONNECTION_STRING"); MariaDbServerVersion serverVersion = new MariaDbServerVersion(ServerVersion.AutoDetect(connectionString)); services.AddDbContextPool <UmaMusumeDbContext>( dbContextOptions => dbContextOptions .UseMySql(connectionString, serverVersion) //.EnableSensitiveDataLogging() // These two calls are optional but help //.EnableDetailedErrors() // with debugging (remove for production). ); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Uma Musume API", Version = "v1.1", Description = "A community API for the mobile game, Uma Musume: Pretty Derby. " + "This is utilizing the \"master.mdb\" file", Contact = new OpenApiContact { Name = "GitHub", Email = string.Empty, Url = new Uri("https://github.com/SimpleSandman/UmaMusumeAPI") }, License = new OpenApiLicense { Name = "Use under Apache 2.0", Url = new Uri("https://www.apache.org/licenses/LICENSE-2.0") } }); // Locate the XML file being generated by ASP.NET in order to use // human-friendly descriptors for Operations, Parameters, and Schemas var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlPath)); }); // Allow "Access-Control-Allow-Origin: *" header services.AddCors(options => { options.AddPolicy("AllowAnyOrigin", builder => { builder.AllowAnyOrigin(); }); }); }
public UmaMusumeDbContext CreateDbContext(string[] args) { /* * When using the Package Manager Console (PMC) to generate code, * set the connection string first for the environment variable, * then call "dotnet-aspnet-codegenerator.exe" normally. */ // PM> $env:MARIA_CONNECTION_STRING='user id=;password=;host=;database=;character set=utf8mb4' // PM> dotnet-aspnet-codegenerator.exe string connectionString = Environment.GetEnvironmentVariable("MARIA_CONNECTION_STRING"); var optionsBuilder = new DbContextOptionsBuilder <UmaMusumeDbContext>(); MariaDbServerVersion serverVersion = new MariaDbServerVersion(ServerVersion.AutoDetect(connectionString)); optionsBuilder.UseMySql(connectionString, serverVersion); return(new UmaMusumeDbContext(optionsBuilder.Options)); }
public MaxscaleDbcontextFixture() { var containerBuilder = new ContainerBuilder(); //maxscale连接地址 //var dbstring = "Server=106.14.139.201;Port=14006;database=adnc_cus;uid=adnc;pwd=123abc;"; var dbstring = "server=106.14.139.201;port=14006;user=adnc;password=123abc;database=adnc_cus"; //注册操作用户 containerBuilder.RegisterType <Operater>() .As <IOperater>() .InstancePerLifetimeScope(); //注册DbContext Options var serverVersion = new MariaDbServerVersion(new Version(10, 5, 4)); containerBuilder.Register <DbContextOptions>(c => { var options = new DbContextOptionsBuilder <AdncDbContext>() .UseLoggerFactory(LoggerFactory.Create(builder => builder.AddDebug())) .UseMySql(dbstring, serverVersion, mySqlOptions => { }) .AddInterceptors(new DefaultDbCommandInterceptor()) .Options; return(options); }).InstancePerLifetimeScope(); //注册EntityInfo containerBuilder.RegisterType <EntityInfo>() .As <IEntityInfo>() .InstancePerLifetimeScope(); //注册DbContext containerBuilder.RegisterType <AdncDbContext>() .InstancePerLifetimeScope(); //注册Adnc.Infra.EfCore AdncCusRepositoryModule.Register(containerBuilder); Container = containerBuilder.Build(); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { var connectionString = $"server={_options.Value.Address};port=3306;user={_options.Value.User};password={_options.Value.Password};database={_options.Value.Database_Name}"; optionsBuilder.UseMySql( connectionString, MariaDbServerVersion.Parse("10.4.12-MariaDB-1:10.4.12+maria~bionic"), MysqlOptions) .UseLoggerFactory(_loggerFactory) .EnableDetailedErrors() ; if (_env.IsDevelopment()) { optionsBuilder.EnableSensitiveDataLogging(); } } }
public CoreServiceFixture() { var containerBuilder = new ContainerBuilder(); var dbstring = "Server=106.14.139.201;Port=13308;database=adnc_cus_dev;uid=root;pwd=alpha.netcore;"; //注册操作用户 containerBuilder.RegisterType <Operater>() .As <IOperater>() .InstancePerLifetimeScope(); //注册DbContext Options containerBuilder.Register <DbContextOptions>(c => { var serverVersion = new MariaDbServerVersion(new Version(10, 5, 4)); return(new DbContextOptionsBuilder <AdncDbContext>() .UseLoggerFactory(LoggerFactory.Create(builder => builder.AddDebug())) .UseMySql(dbstring, serverVersion).Options); }) .InstancePerLifetimeScope(); //注册DbContext containerBuilder.RegisterType <AdncDbContext>().InstancePerLifetimeScope(); //注册事件发布者 containerBuilder.RegisterType <NullCapPublisher>() .As <ICapPublisher>().SingleInstance(); //注册Adnc.Infra.EfCore AdncInfraEfCoreModule.Register(containerBuilder); //注册 Adnc.Cus.Core AdncCusRepositoryModule.Register(containerBuilder); Container = containerBuilder.Build(); }
// This method gets called by the runtime. Use this method to add services to the container. public void 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; // }); AuthServerTypeAdapterConfig.Configure(); var mysqlConnectionString = Configuration.GetConnectionString("MysqlConnectionString"); var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name; var dbServerVersion = new MariaDbServerVersion(new Version(10, 6, 4)); Action <DbContextOptionsBuilder> dbOptions = options => { options.UseMySql(mysqlConnectionString, dbServerVersion, builder => { builder.MigrationsAssembly(migrationsAssembly); builder.EnableRetryOnFailure(5, new TimeSpan(0, 0, 10), new List <int> { 1, 2, 3, 4 }); } ); options .UseOpenIddict <ApplicationClient, ApplicationAuthorization, ApplicationScope, ApplicationToken, Guid>(); }; services.AddDbContext <ApplicationDbContext>(dbOptions); services.AddPooledDbContextFactory <ApplicationDbContext>(dbOptions); services.AddHostedService <TestData>(); services.AddIdentity <ApplicationUser, ApplicationRole>() .AddDefaultTokenProviders() .AddEntityFrameworkStores <ApplicationDbContext>(); services.Configure <IdentityOptions>(options => { options.ClaimsIdentity.UserNameClaimType = OpenIddictConstants.Claims.Name; options.ClaimsIdentity.UserIdClaimType = OpenIddictConstants.Claims.Subject; options.ClaimsIdentity.RoleClaimType = OpenIddictConstants.Claims.Role; options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789- "; }); // services.ConfigureApplicationCookie(o => { o.LoginPath = "/login"; }); services.AddDbServices(); services.AddGraphQlServices(); services.AddSingleton <IAuthorizationHandler, AdministratorHandler>() .AddScoped <IStores, Stores>() .AddScoped <IControllerUtils, ControllerUtils>(); services.AddOpenIdDictServices(_env, Configuration.Get <TokenSigningConfiguration>()); services.AddAuthorization(options => { options.AddPolicy("Administrator", policy => { policy.Requirements.Add(new AdministratorRequirement()); }); }); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, opts => { opts.LoginPath = "/login"; }); services.AddCors(o => { o.AddPolicy(Cors, builder => { builder.WithOrigins("https://localhost"); }); }); services.AddSpaStaticFiles(configuration => { configuration.RootPath = "wwwroot"; }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "AuthServer API", Version = "v1", Description = "AuthServer Idp" }); c.DocumentFilter <DocumentFiler>(); c.DocumentFilter <ModelFilter>(); c.UseInlineDefinitionsForEnums(); }); services.AddSwaggerGenNewtonsoftSupport(); services.AddGraphQL(); services.AddControllers(o => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); o.Filters.Add(new AuthorizeFilter(policy)); o.EnableEndpointRouting = true; }).AddNewtonsoftJson(o => o.SerializerSettings.Converters.Add(new StringEnumConverter()) ); }
/// <summary> /// Configures the services. /// </summary> /// <param name="services">The services.</param> /// <remarks> /// 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. /// </remarks> public void ConfigureServices(IServiceCollection services) { // Setup Razor and Web API services.AddControllersWithViews(); services.AddRazorPages(); // Add supported translation providers services.AddSingleton <IProvider, BibleApi>(); services.AddSingleton <IProvider, BibliaApi>(); services.AddSingleton <IProvider, DigitalBiblePlatformApi>(); services.AddSingleton <IProvider, EsvBible>(); services.AddSingleton <IProvider, Laodiceans>(); services.AddSingleton <IProvider, NetBible>(); services.AddSingleton <IProvider, NltBible>(); services.AddSingleton <IProvider, SblGnt>(); // Add options for providers that require them services.Configure <BibleApiOptions>(this.Configuration.GetSection("Providers:BibleApi")); services.Configure <BibliaApiOptions>(this.Configuration.GetSection("Providers:BibliaApi")); services.Configure <DigitalBiblePlatformApiOptions>(this.Configuration.GetSection("Providers:DigitalBiblePlatformApi")); services.Configure <EsvBibleOptions>(this.Configuration.GetSection("Providers:EsvBible")); services.Configure <NltBibleOptions>(this.Configuration.GetSection("Providers:NltBible")); // Load the caching provider CacheSettings?cacheConfig = this.Configuration.GetSection("Providers:Cache").Get <CacheSettings>(); switch (cacheConfig?.DatabaseProvider.ToUpperInvariant()) { case "MSSQL": services.Configure <SqlServerCacheOptions>(this.Configuration.GetSection("Providers:Cache")); services.AddSingleton <IDistributedCache, SqlServerCache>(); break; case "MARIADB": case "MYSQL": services.Configure <MySqlCacheOptions>(this.Configuration.GetSection("Providers:Cache")); services.AddSingleton <IDistributedCache, MySqlCache>(); break; default: services.AddSingleton <IDistributedCache, MemoryDistributedCache>(); break; } // Load the statistics context StatisticsSettings?statisticsConfig = this.Configuration.GetSection("Providers:Statistics").Get <StatisticsSettings>(); ServerVersion serverVersion; switch (statisticsConfig?.DatabaseProvider?.ToUpperInvariant()) { case "MARIADB": if (string.IsNullOrWhiteSpace(statisticsConfig.DatabaseVersion)) { serverVersion = MariaDbServerVersion.LatestSupportedServerVersion; } else { serverVersion = new MariaDbServerVersion(statisticsConfig.DatabaseVersion); } if (!string.IsNullOrWhiteSpace(statisticsConfig.ConnectionString)) { services.AddDbContext <StatisticsContext>(options => options.UseMySql(statisticsConfig.ConnectionString, serverVersion)); } break; case "MSSQL": if (!string.IsNullOrWhiteSpace(statisticsConfig.ConnectionString)) { services.AddDbContext <StatisticsContext>(options => options.UseSqlServer(statisticsConfig.ConnectionString)); } break; case "MYSQL": if (string.IsNullOrWhiteSpace(statisticsConfig.DatabaseVersion)) { serverVersion = MySqlServerVersion.LatestSupportedServerVersion; } else { serverVersion = new MySqlServerVersion(statisticsConfig.DatabaseVersion); } if (!string.IsNullOrWhiteSpace(statisticsConfig.ConnectionString)) { services.AddDbContext <StatisticsContext>(options => options.UseMySql(statisticsConfig.ConnectionString, serverVersion)); } break; } }
public UnitTestDeviceController() { optionsBuilder = new DbContextOptionsBuilder <HomeSurveillanceDBContext>().UseMySql(connectionString, MariaDbServerVersion.AutoDetect(connectionString)); context = new HomeSurveillanceDBContext(optionsBuilder.Options); DeviceController = new DeviceController(context); context.Database.EnsureCreated(); }
public void ConfigureServices(IServiceCollection services) { //string mySqlConnectionStr = Configuration.GetConnectionString("RemoteConnection"); string mySqlConnectionStr = Configuration.GetConnectionString("DockerConnection"); //string mySqlConnectionStr = Configuration.GetConnectionString("RPDockerConnection"); services.AddDbContextPool<HomeSurveillanceDBContext>(o => o.UseMySql(mySqlConnectionStr, MariaDbServerVersion.AutoDetect(mySqlConnectionStr))); // Identity services.AddIdentity<User, IdentityRole>() .AddEntityFrameworkStores<HomeSurveillanceDBContext>() .AddDefaultTokenProviders(); //Auth services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) //Jwt Token .AddJwtBearer(options => { options.SaveToken = true; options.RequireHttpsMetadata = true; options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidateAudience = true, ValidAudience = Configuration["JwtConfig:ValidAudience"], ValidIssuer = Configuration["JwtConfig:ValidIssuer"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtConfig:Secret"])), RequireExpirationTime = true, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; //Add Check for JWT-token in cookies options.Events = new JwtBearerEvents { OnMessageReceived = context => { context.Token = context.Request.Cookies["JwtToken"]; return Task.CompletedTask; }, }; }); //Set global Authorization services.AddAuthorization(options => { options.FallbackPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); }); services.AddControllersWithViews(); }