コード例 #1
0
        /// <summary>
        ///     Configures the context to connect to a named in-memory database.
        ///     The in-memory database is shared anywhere the same name is used, but only for a given
        ///     service provider.
        /// </summary>
        /// <param name="optionsBuilder"> The builder being used to configure the context. </param>
        /// <param name="databaseName">
        ///     The name of the in-memory database. This allows the scope of the in-memory database to be controlled
        ///     independently of the context. The in-memory database is shared anywhere the same name is used.
        /// </param>
        /// <param name="databaseRoot">
        ///     All in-memory databases will be rooted in this object, allowing the application
        ///     to control their lifetime. This is useful when sometimes the context instance
        ///     is created explicitly with <see langword="new" /> while at other times it is resolved using dependency injection.
        /// </param>
        /// <param name="inMemoryOptionsAction">An optional action to allow additional in-memory specific configuration.</param>
        /// <returns> The options builder so that further configuration can be chained. </returns>
        public static DbContextOptionsBuilder UseInMemoryDatabase(
            [NotNull] this DbContextOptionsBuilder optionsBuilder,
            [NotNull] string databaseName,
            [CanBeNull] InMemoryDatabaseRoot databaseRoot,
            [CanBeNull] Action <InMemoryDbContextOptionsBuilder> inMemoryOptionsAction = null)
        {
            Check.NotNull(optionsBuilder, nameof(optionsBuilder));
            Check.NotEmpty(databaseName, nameof(databaseName));

            var extension = optionsBuilder.Options.FindExtension <InMemoryOptionsExtension>()
                            ?? new InMemoryOptionsExtension();

            extension = extension.WithStoreName(databaseName);

            if (databaseRoot != null)
            {
                extension = extension.WithDatabaseRoot(databaseRoot);
            }

            ConfigureWarnings(optionsBuilder);

            ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension);

            inMemoryOptionsAction?.Invoke(new InMemoryDbContextOptionsBuilder(optionsBuilder));

            return(optionsBuilder);
        }
コード例 #2
0
 public PetsContextWithData(
     string databaseName,
     InMemoryDatabaseRoot root = null,
     IServiceProvider internalServiceProvider = null)
     : base(databaseName, root, internalServiceProvider)
 {
 }
コード例 #3
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                // Create a new service provider.
                var serviceProvider = new ServiceCollection()
                                      .AddEntityFrameworkInMemoryDatabase()
                                      .BuildServiceProvider();

                var root = new InMemoryDatabaseRoot();

                //services.AddDbContext<IFlyinlineDbContext, FlyinlineDbContext>(options =>
                //{
                //    options.UseInMemoryDatabase("InMemoryDbForTesting", root);
                //    options.UseInternalServiceProvider(serviceProvider);
                //});

                //add settings file to config providers:
                var _configuration = FunctionsHostBuilderExtensions.GetConfigurationWithAppSettings(services);
                // builder.Services.Replace(ServiceDescriptor.Singleton(typeof(IConfiguration), _configuration));
                // _credentialSettings = _configuration.GetSection("Values:Credentials").Get<CredentialSettings>();



                services.AddDbContext <IFlyinlineDbContext, FlyinlineDbContext>(options =>
                {
                    options.UseSqlServer(_configuration.GetConnectionString("flyinline_db"));
                });


                // Build the service provider.
                var sp = services.BuildServiceProvider();
                // Create a scope to obtain a reference to the database
                // context (NorthwindDbContext)
                using (var scope = sp.CreateScope())
                {
                    var scopedServices = scope.ServiceProvider;
                    var context        = scopedServices.GetRequiredService <IFlyinlineDbContext>();
                    var logger         = scopedServices
                                         .GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >();


                    var concreteContext = (FlyinlineDbContext)context;

                    // Ensure the database is created.
                    concreteContext.Database.EnsureCreated();

                    try
                    {
                        // Seed the database with test data.
                        Utilities.InitializeDbForTests(concreteContext);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, $"An error occurred seeding the " +
                                        "database with test messages. Error: {ex.Message}");
                    }
                }
            });
        }
コード例 #4
0
        public async Task Test4()
        {
            output.WriteLine($"Test {nameof(Test4)} is running");

            // Seed seeds using the specified startup object.
            // This way we can provide data from the test to the startup.
            // Typical case, we want the inmemory database to be unique per test.
            // We will create the database root in the test and provide it both to
            // the startup and to the object creator.

            var databaseName = Guid.NewGuid().ToString();
            var databaseRoot = new InMemoryDatabaseRoot();

            var outputSink = new InternalQueueOutputSink();
            var startup    = new SampleStartupForUnitTests(outputSink)
            {
                DatabaseName = databaseName,
                DatabaseRoot = databaseRoot
            };

            var baseCampTrack = await Get.Yield <MountEverestBaseCampTrack.Yield>(startup, outputSink);

            output.WriteLine(outputSink.GetOutputAsString());

            var projectService = objectCreator.WithLocalInMemoryDatabase(databaseName, databaseRoot).Create <IProjectService>();
            var projects       = (await projectService.GetAll()).Value;

            Assert.Contains(projects, project => project.Name == SomeAlwaysRequiredProject.Yield.SomeAlwaysRequiredProjectName);
            Assert.Equal(2, projects.Count);

            projectService = objectCreator.WithLocalInMemoryDatabase(Guid.NewGuid().ToString(), new InMemoryDatabaseRoot()).Create <IProjectService>();
            projects       = (await projectService.GetAll()).Value;
            Assert.Empty(projects);
        }
コード例 #5
0
        public void ShouldSaveWithRoot()
        {
            // Given
            var root = new InMemoryDatabaseRoot();

            var options = new DbContextOptionsBuilder <DataContext>().UseInMemoryDatabase(Guid.NewGuid().ToString(), root)
                          .Options;

            // When
            using (var context = new DataContext(options))
            {
                context.Add(new Person
                {
                    Comment = new TransliteratedString("Comment"),
                    Names   = new List <PersonNames>
                    {
                        new PersonNames {
                            Value = new TransliteratedString("Name")
                        }
                    }
                });

                context.SaveChanges();
            }

            // Then
            using (var context = new DataContext(options))
            {
                Assert.Single(context.Set <Person>());
                Assert.Single(context.Set <PersonNames>());
            }
        }
コード例 #6
0
        public static DbContextOptionsBuilder UseLocalStorageDatabase(
            this DbContextOptionsBuilder optionsBuilder,
            IJSRuntime JSRuntime,
            string serializer   = "json",
            string databaseName = "",
            string password     = "",
            InMemoryDatabaseRoot databaseRoot = null,
            Action <InMemoryDbContextOptionsBuilder> inMemoryOptionsAction = null)
        {
            var filemanager = string.IsNullOrEmpty(password) ? "default" : $"encrypted:{password}";
            var options     = new LocalStorageOptions()
            {
                Serializer = serializer, DatabaseName = databaseName, Password = password, FileManager = filemanager, Location = null
            };

            //var dbServices = new ServiceCollection();
            //dbServices.AddEntityFrameworkInMemoryDatabase();
            //dbServices.AddSingleton(options);

            //dbServices.AddEntityFrameworkLocalStorageDatabase(JSRuntime);

            //optionsBuilder.UseInternalServiceProvider(dbServices.BuildServiceProvider()).UseFileContextDatabase(serializer, filemanager, databaseName, null, databaseRoot, inMemoryOptionsAction);

            //optionsBuilder.UseInternalServiceProvider(dbServices.BuildServiceProvider()).UseInMemoryDatabase(databaseName, databaseRoot, inMemoryOptionsAction);

            //optionsBuilder.UseInternalServiceProvider(dbServices.BuildServiceProvider()).UseInMemoryDatabase(databaseName, databaseRoot, inMemoryOptionsAction);

            ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(new LocalStorageOptionsExtension(JSRuntime, options));
            optionsBuilder.UseInMemoryDatabase(databaseName, databaseRoot, inMemoryOptionsAction);

            return(optionsBuilder);
        }
コード例 #7
0
 public TestDbContext(int tenantId, int userId, InMemoryDatabaseRoot dbRoot = null,
                      bool isAdminContext = false) : base(
         tenantId, userId,
         isAdminContext)
 {
     _dbRoot = dbRoot;
 }
コード例 #8
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            var integrationTestConfig = new ConfigurationBuilder()
                                        .AddJsonFile("integrationtestsettings.json")
                                        .Build();

            builder
            .UseSolutionRelativeContentRoot("src/GraphIoT.Digitalstrom")
            .ConfigureAppConfiguration(config =>
            {
                config.AddConfiguration(integrationTestConfig);
            })
            .ConfigureServices(services =>
            {
                // Build a http mock for requests to the digitalstrom server
                services.AddSingleton(fac =>
                {
                    var mockHttp = new MockHttpMessageHandler();
                    mockHttp.AddAuthMock()
                    .AddStructureMock()
                    .AddCircuitZonesMocks(new Zone[] { 4, 32027 })
                    .AddEnergyMeteringMocks()
                    .AddSensorMocks()
                    .AddInitialAndSubscribeMocks();

                    MockedEventResponse = mockHttp.When($"{MockDigitalstromConnection.BaseUri}/json/event/get")
                                          .WithExactQueryString($"subscriptionID=10&timeout=60000&token={MockDigitalstromConnection.AppToken}")
                                          .Respond("application/json", SceneCommand.Preset0.ToMockedSceneEvent());

                    return(mockHttp);
                });

                // Build a database context using an in-memory database for testing
                var dbRoot = new InMemoryDatabaseRoot();
                void dbConfig(DbContextOptionsBuilder options)
                {
                    options.UseInMemoryDatabase("InMemoryDbIntegrationTest", dbRoot);
                    options.UseInternalServiceProvider(new ServiceCollection()
                                                       .AddEntityFrameworkInMemoryDatabase()
                                                       .BuildServiceProvider());
                }

                // Add all digitalstrom services using the mocked in-memory db
                services.AddDigitalstromHost <IntegrationTestDbContext>(dbConfig,
                                                                        integrationTestConfig.GetSection("DigitalstromConfig"),
                                                                        integrationTestConfig.GetSection("TokenStoreConfig"),
                                                                        integrationTestConfig.GetSection("Network")
                                                                        );

                // Replace the digitalstrom connection provider with a http mock for testing
                var existingProvider = services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(IDigitalstromConnectionProvider));
                if (existingProvider != null)
                {
                    services.Remove(existingProvider);
                }
                services.AddTransient <IDigitalstromConnectionProvider, DigitalstromConnectionProvider>(fac =>
                                                                                                        fac.GetRequiredService <MockHttpMessageHandler>().ToMockProvider());
            });
        }
コード例 #9
0
 public TestingDBContext()
 {
     this.currentDbNumber = Interlocked.Increment(ref uniqueDbNumber);
     this.databaseRoot    = new InMemoryDatabaseRoot();
     this.defaultDb       = new Lazy <AppDbContext>(CreateDb);
     DbFactory            = new TestAppDbContextFactory(CreateDb);
     this.cancellation    = new CancellationTokenSource();
 }
コード例 #10
0
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public virtual InMemoryOptionsExtension WithDatabaseRoot([NotNull] InMemoryDatabaseRoot databaseRoot)
        {
            var clone = Clone();

            clone._databaseRoot = databaseRoot;

            return(clone);
        }
コード例 #11
0
 /// <summary>
 ///     Configures the context to connect to an in-memory database.
 ///     The in-memory database is shared anywhere the same name is used, but only for a given
 ///     service provider.
 /// </summary>
 /// <typeparam name="TContext"> The type of context being configured. </typeparam>
 /// <param name="optionsBuilder"> The builder being used to configure the context. </param>
 /// <param name="databaseName">
 ///     The name of the in-memory database. This allows the scope of the in-memory database to be controlled
 ///     independently of the context. The in-memory database is shared anywhere the same name is used.
 /// </param>
 /// <param name="databaseRoot">
 ///     All in-memory databases will be rooted in this object, allowing the application
 ///     to control their lifetime. This is useful when sometimes the context instance
 ///     is created explicitly with <see langword="new" /> while at other times it is resolved using dependency injection.
 /// </param>
 /// <param name="inMemoryOptionsAction">An optional action to allow additional in-memory specific configuration.</param>
 /// <returns> The options builder so that further configuration can be chained. </returns>
 public static DbContextOptionsBuilder <TContext> UseInMemoryDatabase <TContext>(
     [NotNull] this DbContextOptionsBuilder <TContext> optionsBuilder,
     [NotNull] string databaseName,
     [CanBeNull] InMemoryDatabaseRoot databaseRoot,
     [CanBeNull] Action <InMemoryDbContextOptionsBuilder> inMemoryOptionsAction = null)
     where TContext : DbContext
 => (DbContextOptionsBuilder <TContext>)UseInMemoryDatabase(
     (DbContextOptionsBuilder)optionsBuilder, databaseName, databaseRoot, inMemoryOptionsAction);
コード例 #12
0
        public WeatherDbContext GetInMemoryDbContext()
        {
            var root           = new InMemoryDatabaseRoot();
            var optionsBuilder = new DbContextOptionsBuilder <WeatherDbContext>();

            optionsBuilder.UseInMemoryDatabase("in-memory", root);
            return(new WeatherDbContext(optionsBuilder.Options));
        }
コード例 #13
0
 public InMemoryDbContextTransactionScope([NotNull] InMemoryDbContextTransactionScopeOptions options) : base(options)
 {
     if (options == null)
     {
         throw new ArgumentNullException(nameof(options));
     }
     _databaseName = options.DatabaseName;
     _databaseRoot = options.DatabaseRoot;
 }
コード例 #14
0
 public static DbContextOptionsBuilder <TContext> UseLocalStorageDatabaseConnectionString <TContext>(
     this DbContextOptionsBuilder <TContext> optionsBuilder,
     IJSRuntime JSRuntime,
     string connectionString,
     InMemoryDatabaseRoot databaseRoot = null,
     Action <InMemoryDbContextOptionsBuilder> inMemoryOptionsAction = null)
     where TContext : DbContext
 => (DbContextOptionsBuilder <TContext>)UseLocalStorageDatabaseConnectionString(
     (DbContextOptionsBuilder)optionsBuilder, JSRuntime, connectionString, databaseRoot, inMemoryOptionsAction);
コード例 #15
0
 public PetsContext(
     string databaseName,
     InMemoryDatabaseRoot root = null,
     IServiceProvider internalServiceProvider = null)
 {
     _databaseName            = databaseName;
     _root                    = root;
     _internalServiceProvider = internalServiceProvider;
 }
コード例 #16
0
 public TestDataInitializer(
     ILoggerFactory loggerFactory,
     IEnumerable <IHttpClientTestDataInitializer> httpClientTestDataInitalizers,
     IEnumerable <IDbContextTestDataInitializer> dbContextTestDataInitializers,
     InMemoryDatabaseRoot databaseRoot)
 {
     _loggerFactory = loggerFactory;
     _httpClientTestDataInitalizers = httpClientTestDataInitalizers;
     _dbContextTestDataInitializers = dbContextTestDataInitializers;
     _databaseRoot = databaseRoot;
 }
コード例 #17
0
 public static DbContextOptionsBuilder <TContext> UseLocalStorageDatabase <TContext>(
     this DbContextOptionsBuilder <TContext> optionsBuilder,
     IJSRuntime JSRuntime,
     string serializer   = "json",
     string databaseName = "",
     string password     = "",
     InMemoryDatabaseRoot databaseRoot = null,
     Action <InMemoryDbContextOptionsBuilder> inMemoryOptionsAction = null)
     where TContext : DbContext
 => (DbContextOptionsBuilder <TContext>)UseLocalStorageDatabase(
     (DbContextOptionsBuilder)optionsBuilder, JSRuntime, serializer, databaseName, password, databaseRoot, inMemoryOptionsAction);
コード例 #18
0
 public InMemoryDbContextTransactionScope(
     string databaseName = null,
     InMemoryDatabaseRoot databaseRoot = null,
     Action <DbContextOptionsBuilder> optionsBuilderAction = null,
     IDbContextActivator activator = null) : this(new InMemoryDbContextTransactionScopeOptions
 {
     DatabaseName = databaseName,
     DatabaseRoot = databaseRoot,
     OptionsBuilderAction = optionsBuilderAction,
 })
 {
 }
コード例 #19
0
ファイル: Startup.cs プロジェクト: ashrafMageed/BookStore
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var dataBaseRoot = new InMemoryDatabaseRoot();

            services.AddDbContext <ApiContext>(opt => opt.UseInMemoryDatabase("BooksDb"));
            services.AddDbContext <OrderContext>(opt => opt.UseInMemoryDatabase("OrdersDb"));
            services.AddDbContext <ShippingContext>(opt => opt.UseInMemoryDatabase("ShippingDb", dataBaseRoot));
            services.AddTransient <PurchaseOrderReceivedHandler>();
            var sp  = services.BuildServiceProvider();
            var bus = new InMemoryMessageBus();

            var optionsBuilder = new DbContextOptionsBuilder <ShippingContext>();

            optionsBuilder.UseInMemoryDatabase("ShippingDb", dataBaseRoot);
            var context = new ShippingContext(optionsBuilder.Options);
            var shippingOrderHandler = new PurchaseOrderReceivedHandler(bus, context);

            bus.RegisterHandler <PurchaseOrderReceived>(e => shippingOrderHandler.Handle(e));

            services.AddSingleton <InMemoryMessageBus>(bus);

            // services.AddAuthentication(options =>
            //   {
            //     options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            //   })
            //     .AddJwtBearer(jwtOptions =>
            //     {
            //       jwtOptions.Authority = $"https://login.microsoftonline.com/tfp/{Configuration["AzureAdB2C:Tenant"]}/{Configuration["AzureAdB2C:Policy"]}/v2.0/";
            //       jwtOptions.Audience = Configuration["AzureAdB2C:ClientId"];
            //       jwtOptions.Events = new JwtBearerEvents
            //       {
            //         OnAuthenticationFailed = AuthenticationFailed
            //       };
            //     });

            services.AddAzureAdB2CAuthentication();

            services.AddMvc(setupAction => {
                var inputFormatter = setupAction.InputFormatters.OfType <JsonInputFormatter>().FirstOrDefault();

                if (inputFormatter != null)
                {
                    inputFormatter.SupportedMediaTypes.Add("application/json-patch+json");
                }
            });
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Books Store", Version = "v1"
                });
            });
        }
コード例 #20
0
        protected override IHost CreateHost(IHostBuilder builder)
        {
            var root = new InMemoryDatabaseRoot();

            builder.ConfigureServices(services =>
            {
                services.RemoveAll(typeof(DbContextOptions <TodoDbContext>));

                services.AddDbContext <TodoDbContext>(options =>
                                                      options.UseInMemoryDatabase("Testing", root));
            });

            return(base.CreateHost(builder));
        }
コード例 #21
0
        public BddDbContext GetDbContext()
        {
            var builder = new DbContextOptionsBuilder <BddDbContext>();

            InMemoryDatabaseRoot _inMemoryDatabaseRoot = new InMemoryDatabaseRoot();

            builder.UseInMemoryDatabase(Guid.NewGuid().ToString(), _inMemoryDatabaseRoot)
            .EnableServiceProviderCaching(false);

            var dbContext = new BddDbContext(builder.Options);

            dbContext.Database.EnsureCreated();
            return(dbContext);
        }
コード例 #22
0
        public void ConfigureServices(IServiceCollection services)
        {
            var inMemoryDatabaseRoot = new InMemoryDatabaseRoot();

            services.AddDbContext <GettingThingsDoneDbContext>(options => options.UseInMemoryDatabase("GettingThingsDoneDatabase", inMemoryDatabaseRoot));

            services.AddScoped(typeof(IRepository <>), typeof(EfRepository <>));
            services.AddScoped(typeof(IAsyncRepository <>), typeof(EfAsyncRepository <>));
            services.AddScoped <IActionService, ActionService>();
            services.AddScoped <IActionListService, ActionListService>();
            services.AddScoped <IProjectService, ProjectService>();

            // Add authentication JWT options settings.
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = "gettingthingsdone.com",
                    ValidAudience    = "gettingthingsdone.com",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["SecurityKey"]))
                };
            });

            // Add custom authorization claim based policy.
            services.AddAuthorization(options =>
            {
                options.AddPolicy(
                    CustomPolicies.OnlyUsersOlderThan,
                    policy => policy
                    .RequireClaim(CustomClaimTypes.DateOfBirth)
                    .AddRequirements(new OlderThanRequirement(50)));
            });

            // Register Older Than authorization handler.
            services.AddSingleton <IAuthorizationHandler, OlderThanAuthorizationHandler>();

            //versioning
            services.AddApiVersioning(v =>
            {
                v.AssumeDefaultVersionWhenUnspecified = true;
                v.ApiVersionReader = new HeaderApiVersionReader("api-version");
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
コード例 #23
0
        public static IEFCoreOrchestrationBuilder UseInMemoryDatabase(
            this IEFCoreOrchestrationBuilder builder,
            string databaseName,
            InMemoryDatabaseRoot databaseRoot,
            Action <InMemoryDbContextOptionsBuilder> inMemoryOptionsAction = null)
        {
            builder.Services.AddSingleton <OrchestrationDbContextExtensions, InMemoryOrchestrationDbContextExtensions>();

            return(builder.ConfigureDbContext(options =>
            {
                options.UseInMemoryDatabase(databaseName, databaseRoot, inMemoryOptions =>
                {
                    inMemoryOptionsAction?.Invoke(inMemoryOptions);
                });
            }));
        }
コード例 #24
0
        public static IServiceCollection AddTestData <TStartup>(this IServiceCollection services)
            where TStartup : class
        {
            var databaseRoot = new InMemoryDatabaseRoot();

            services.AddDbContext <CoreDbContext>(optionsBuilder =>
                                                  optionsBuilder.UseInMemoryDatabase(databaseName: "Test.Data", databaseRoot: databaseRoot));

            services.AddSingleton <ITestDataInitializer <TStartup> >(sp =>
                                                                     ActivatorUtilities.CreateInstance <TestDataInitializer <TStartup> >(sp, databaseRoot));

            services.AddTransient <IDbContextTestDataInitializer, RegionInitializer>();

            services.AddTransient <IHttpClientTestDataInitializer, RegionMembershipInitializer>();

            return(services);
        }
コード例 #25
0
        public virtual void TestSetup()
        {
            HttpClient httpClient;
            var        databaseRoot = new InMemoryDatabaseRoot();

            contextOptions = new DbContextOptionsBuilder <DataRetrievalContext>()
                             .UseInMemoryDatabase(DatabaseName, databaseRoot)
                             .Options;

            var webAppFactory = new InMemoryFactory <FakeResponseServer.Startup>(DatabaseName, databaseRoot);

            httpClient = webAppFactory.CreateClient(FakeServerAddress);

            externalAPICaller = new ExternalAPICaller(httpClient);

            FakeDataRetrievalSourceFactory = () => new FakeDataRetrievalSource(externalAPICaller, FakeServerAddress);
        }
コード例 #26
0
        public static DbContextOptionsBuilder UseLocalStorageDatabaseConnectionString(
            this DbContextOptionsBuilder optionsBuilder,
            IJSRuntime JSRuntime,
            string connectionString,
            InMemoryDatabaseRoot databaseRoot = null,
            Action <InMemoryDbContextOptionsBuilder> inMemoryOptionsAction = null)
        {
            string[] connectionStringParts = connectionString.Split(';');
            Dictionary <string, string> connectionStringSplitted = connectionStringParts
                                                                   .Select(segment => segment.Split('='))
                                                                   .ToDictionary(parts => parts[0].Trim().ToLowerInvariant(), parts => parts[1].Trim());

            return(UseLocalStorageDatabase(optionsBuilder,
                                           JSRuntime,
                                           connectionStringSplitted.GetValueOrDefault("serializer"),
                                           connectionStringSplitted.GetValueOrDefault("databasename"),
                                           connectionStringSplitted.GetValueOrDefault("password")
                                           , databaseRoot, inMemoryOptionsAction));
        }
コード例 #27
0
    public void Generators_are_associated_with_database_root()
    {
        var serviceProvider1 = new ServiceCollection()
                               .AddEntityFrameworkInMemoryDatabase()
                               .BuildServiceProvider(validateScopes: true);

        var serviceProvider2 = new ServiceCollection()
                               .AddEntityFrameworkInMemoryDatabase()
                               .BuildServiceProvider(validateScopes: true);

        var root = new InMemoryDatabaseRoot();

        var macs   = new Mac[2];
        var toasts = new Toast[2];

        using (var context = new PetsContext("Drink", root, serviceProvider1))
        {
            macs[0]   = context.Add(new Mac()).Entity;
            toasts[0] = context.Add(new Toast()).Entity;

            Assert.Equal(1, macs[0].Id);
            Assert.Equal(1, toasts[0].Id);

            context.SaveChanges();
        }

        using (var context = new PetsContext("Drink", root, serviceProvider2))
        {
            macs[1]   = context.Add(new Mac()).Entity;
            toasts[1] = context.Add(new Toast()).Entity;

            Assert.Equal(2, macs[1].Id);
            Assert.Equal(2, toasts[1].Id);

            context.SaveChanges();
        }

        Assert.Equal(1, macs[0].Id);
        Assert.Equal(1, toasts[0].Id);
        Assert.Equal(2, macs[1].Id);
        Assert.Equal(2, toasts[1].Id);
    }
コード例 #28
0
        public async Task Test()
        {
            try
            {
                var dbRoot = new InMemoryDatabaseRoot();

                void Callback(IServiceCollection services) =>
                services.AddDbContext <OrleansEFContext>(options =>
                                                         options.UseInMemoryDatabase(
                                                             databaseName: "orleans_ef_test",
                                                             databaseRoot: dbRoot
                                                             )
                                                         );

                await TestSuite.Run(1000, Callback);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
コード例 #29
0
        private static TContext AddDbContext <TContext>(ArrangeBuilder arrangeBuilder)
            where TContext : DbContext
        {
            if (arrangeBuilder.IsTypeCached <TContext>(out var result))
            {
                return(result);
            }

            var root = new InMemoryDatabaseRoot();
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddDbContext <TContext>(config => config.UseInMemoryDatabase(arrangeBuilder.GetHashCode().ToString(), root)
                                                      .ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning)));

            arrangeBuilder.UseContainerBuilder((c) => c.Populate(serviceCollection));

            var db = serviceCollection.BuildServiceProvider().GetService <TContext>();

            arrangeBuilder.AddTypeToCache(db);

            return(db);
        }
コード例 #30
0
        public static void TestSetup(IObjectContainer objectContainer)
        {
            HttpClient httpClient;

            databaseRoot   = new InMemoryDatabaseRoot();
            contextOptions = new DbContextOptionsBuilder <DataRetrievalContext>()
                             .UseInMemoryDatabase(DatabaseName, databaseRoot).Options;
            var webAppFactory = new InMemoryFactory <FakeResponseServer.Startup>(DatabaseName, databaseRoot);

            httpClient = webAppFactory.CreateClient("http://localhost:2222");

            var spotifyClient = new ExternalAPICaller(httpClient);

            var dataSource = new DataPort(contextOptions, spotifyClient);

            clientDriver = new ApiClientDriver();
            clientDriver.SetUp(dataSource.ExternalAPIGateway);

            objectContainer.RegisterInstanceAs <IClientDriver>(clientDriver);
            objectContainer.RegisterInstanceAs(dataSource);

            Thread.Sleep(TimeSpan.FromSeconds(1));
        }