public async Task ShouldAddProduct() { Product productMock = new Product() { catogeryId = 1, ProductId = 3, ProductName = "KotmaleMilkPowder" }; var services = new ServiceCollection().AddEntityFrameworkInMemoryDatabase(); services.AddSingleton(_mockEnvironment.Object); services.AddDbContext <ShoppingDBContext>(options => { options.UseInMemoryDatabase("TestDB"); }); var serviceProvider = services.BuildServiceProvider(); using (var scope = serviceProvider.CreateScope()) { var scopedServices = scope.ServiceProvider; var shoppingDBContext = scopedServices.GetRequiredService <ShoppingDBContext>(); DbContextSeed.SeedAsync(shoppingDBContext).Wait(); var genericRepository = new GenericRepository <Product>(shoppingDBContext); var product = await genericRepository.AddAsync(productMock).ConfigureAwait(false); Assert.Equal(productMock.catogeryId, product.catogeryId); Assert.Equal(productMock.ProductId, product.ProductId); Assert.Equal(productMock.ProductName, product.ProductName); Assert.NotNull(genericRepository.GetAsync(3)); } }
public static async Task Main(string[] args) { //CreateHostBuilder(args).Build().Run(); var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var loggerFactory = services.GetRequiredService <ILoggerFactory>(); try { var context = services.GetRequiredService <ApplicationDbContext>(); var userManager = services.GetRequiredService <UserManager <User> >(); await context.Database.MigrateAsync(); await DbContextSeed.SeedAsync(context, scope.ServiceProvider, loggerFactory); } catch (Exception ex) { var logger = loggerFactory.CreateLogger <Program>(); logger.LogError(ex, "An error occurred during migration"); throw; } } host.Run(); }
public async Task ShouldRetrieveProducts_ToGivenCategory() { var services = new ServiceCollection().AddEntityFrameworkInMemoryDatabase(); services.AddSingleton(_webHostEnvironmentMock.Object); services.AddDbContext <DataContext>(options => { options.UseInMemoryDatabase("InMemoryDB"); }); // mapper var config = new MapperConfiguration(cfg => { cfg.AddProfile <AutoMapperProfiles>(); }); IMapper mapper = config.CreateMapper(); var serviceProvider = services.BuildServiceProvider(); using (var scope = serviceProvider.CreateScope()) { var scopedServices = scope.ServiceProvider; var dataContext = scopedServices.GetRequiredService <DataContext>(); DbContextSeed.SeedAsync(dataContext).Wait(); var productRepository = new ProductRepository(dataContext, mapper); var products = await productRepository.GetProducts(1).ConfigureAwait(false); var productList = products.ToList(); Assert.Equal(2, productList.Count); } }
public async Task ShouldRetrieveBillingUser() { var services = new ServiceCollection().AddEntityFrameworkInMemoryDatabase(); services.AddSingleton(_webHostEnvironmentMock.Object); services.AddDbContext <DataContext>(options => { options.UseInMemoryDatabase("InMemoryDB"); }); // mapper var config = new MapperConfiguration(cfg => { cfg.AddProfile <AutoMapperProfiles>(); }); IMapper mapper = config.CreateMapper(); var serviceProvider = services.BuildServiceProvider(); using (var scope = serviceProvider.CreateScope()) { var scopedServices = scope.ServiceProvider; var dataContext = scopedServices.GetRequiredService <DataContext>(); DbContextSeed.SeedAsync(dataContext).Wait(); var paymentRepository = new PaymentRepository(dataContext, mapper); UserForRegisterDto userDetails = await paymentRepository.GetBillingUser(1).ConfigureAwait(false); Assert.Equal("Nemo", userDetails.FirstName); } }
public async Task ShouldretrieveproductForTheGivenId(int id) { var services = new ServiceCollection().AddEntityFrameworkInMemoryDatabase(); services.AddSingleton(_mockEnvironment.Object); services.AddDbContext <ShoppingDBContext>(options => { options.UseInMemoryDatabase("TestDB"); }); var serviceProvider = services.BuildServiceProvider(); using (var scope = serviceProvider.CreateScope()) { var scopedServices = scope.ServiceProvider; var shoppingDBContext = scopedServices.GetRequiredService <ShoppingDBContext>(); DbContextSeed.SeedAsync(shoppingDBContext).Wait(); var genericRepository = new GenericRepository <Product>(shoppingDBContext); Product prod = await genericRepository.GetAsync(id).ConfigureAwait(false); Assert.NotNull(prod); Assert.Equal(id, prod.ProductId); } }
public static void Main(string[] args) { var host = CreateWebHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { //Tạo và phân quyền cho người dùng var serviceProvider = services.GetRequiredService <IServiceProvider>(); var configuration = services.GetRequiredService <IConfiguration>(); AuthorizeSeed.CreateRoles(serviceProvider, configuration).Wait(); //Tạo csdl mẫu khi chạy nếu csdl = null var context = services.GetRequiredService <ApplicationDbContext>(); context.Database.Migrate(); DbContextSeed.Seed(services); } catch (Exception ex) { var logger = services.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "Loi trong run vui long xem lai thong tin ."); } } host.Run(); }
public static void Main(string[] args) { var host = BuildWebHost(args); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; UserManager <IdentityUser> userManager = services.GetRequiredService <UserManager <IdentityUser> >(); RoleManager <IdentityRole> roleManager = services.GetRequiredService <RoleManager <IdentityRole> >(); DbContextSeed.Seed(userManager, roleManager).Wait(); } host.Run(); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureServices(async services => { // Create a new service provider. var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); // Add a database context (AppDbContext) using an in-memory // database for testing. services.AddDbContext <PaymentDbContext>(options => { options.UseInMemoryDatabase("PaymentDb"); options.UseInternalServiceProvider(serviceProvider); }); //services.AddTransient<IPaymentRepository, PaymentRepository>(); services.AddTransient <IRepositoryWrapper, RepositoryWrapper>(); // Build the service provider. var sp = services.BuildServiceProvider(); // Create a scope to obtain a reference to the database // context (AppDbContext). using (var scope = sp.CreateScope()) { var scopedServices = scope.ServiceProvider; var context = scopedServices.GetRequiredService <PaymentDbContext>(); var logger = scopedServices .GetRequiredService <ILogger <ApiWebApplicationFactory <TStartup> > >(); // Ensure the database is created. //context.Database.EnsureCreated(); try { // Seed the database with test data. await DbContextSeed.SeedPaymentDataAsync(context); } catch (Exception ex) { logger.LogError(ex, "An error occurred seeding the " + $"database with test messages. Error: {ex.Message}"); } } }); }
public static IApplicationBuilder UseConfig(this IApplicationBuilder app) { app.UseRouting(); app.UseCors("AllowSameDomain"); //跨域 app.UseAuthentication(); //认证 app.UseAuthorization(); //授权 app.UseHealthChecks("/health"); //健康检查 app.UseErrorHandling(); //异常处理 app.UseSwaggerInfo(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHub <ProjectHub>("/project").RequireCors(t => t.WithOrigins(new string[] { "null" }).AllowAnyMethod().AllowAnyHeader().AllowCredentials()); }); app.UseIdentityServer(); DbContextSeed.SeedAsync(app.ApplicationServices).Wait();//启动初始化数据 return(app); }
public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); // 2.Find the service layer within our scope. using (var scope = host.Services.CreateScope()) { //3. Get the instance of DBContext in our services layer var services = scope.ServiceProvider; var context = services.GetRequiredService <ApiContext>(); //4. Call the DataGenerator to create sample data DbContextSeed.Initialize(services); } //Continue to run the application host.Run(); }
/// <summary> /// 中间件管道 /// </summary> /// <param name="app"></param> /// <param name="env"></param> public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseHealthChecks("/health"); app.RegisterToConsul(Configuration, lifetime); app.UseApiVersioning(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); DbContextSeed.SeedAsync(app).Wait(); }
public async static Task Main(string[] args) { // throttle the thread pool (set available threads to amount of processors) ThreadPool.SetMaxThreads(Environment.ProcessorCount, Environment.ProcessorCount); var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var appDbContext = services.GetRequiredService <PaymentDbContext>(); appDbContext.Database.EnsureDeleted(); appDbContext.Database.Migrate(); await DbContextSeed.SeedPaymentDataAsync(appDbContext); var userDbContext = services.GetRequiredService <UserDbContext>(); userDbContext.Database.EnsureDeleted(); userDbContext.Database.Migrate(); await DbContextSeed.SeedUserDataAsync(userDbContext); } catch (Exception ex) { var logger = scope.ServiceProvider.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred while migrating the database."); throw; } } await host.RunAsync(); }
public async Task ShouldretrieveAllCategories() { var services = new ServiceCollection().AddEntityFrameworkInMemoryDatabase(); services.AddSingleton(_webHostEnvironmentMock.Object); services.AddDbContext <DataContext>(options => { options.UseInMemoryDatabase("InMemoryDB"); }); //var configuration = new MapperConfiguration(c => c.AddMaps(Assembly.Load("AutumnStore.Test"))); //var mapper = new Mapper(configuration); // mapper var config = new MapperConfiguration(cfg => { cfg.AddProfile <AutoMapperProfiles>(); }); IMapper mapper = config.CreateMapper(); var serviceProvider = services.BuildServiceProvider(); using (var scope = serviceProvider.CreateScope()) { var scopedServices = scope.ServiceProvider; var dataContext = scopedServices.GetRequiredService <DataContext>(); DbContextSeed.SeedAsync(dataContext).Wait(); //_mapperMock.Setup(m => m.Map<Category, CategoryDto>).Returns(categoryList); var categoryRepository = new CategoryRepository(dataContext, mapper); List <CategoryDto> categoryList = await categoryRepository.GetCategories().ConfigureAwait(false); //.ProjectTo<CategoryDto>(mapper.ConfigurationProvider).ConfigureAwait(false); //Assert.IsAssignableFrom<CategoryDto>(Category); Assert.Equal(2, categoryList.Count); } }
public async Task ShouldFindProductByGivenId() { var services = new ServiceCollection().AddEntityFrameworkInMemoryDatabase(); services.AddSingleton(_mockEnvironment.Object); services.AddDbContext <ShoppingDBContext>(options => { options.UseInMemoryDatabase("TestDB"); }); var serviceProvider = services.BuildServiceProvider(); using (var scope = serviceProvider.CreateScope()) { var scopedServices = scope.ServiceProvider; var shoppingDBContext = scopedServices.GetRequiredService <ShoppingDBContext>(); DbContextSeed.SeedAsync(shoppingDBContext).Wait(); var genericRepository = new GenericRepository <Product>(shoppingDBContext); IList <Product> prodlist = await genericRepository.FindAsync(x => x.catogeryId == 1).ConfigureAwait(false); Assert.Equal(2, prodlist.Count); } }
public static async Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var loggerFactory = services.GetRequiredService <ILoggerFactory>(); try { var databaseContext = services.GetRequiredService <BarracudaDbContext>(); var userManager = services.GetRequiredService <UserManager <ApplicationUser> >(); var roleManager = services.GetRequiredService <RoleManager <IdentityRole> >(); await DbContextSeed.SeedAsync(userManager, roleManager, databaseContext); } catch (Exception ex) { var logger = loggerFactory.CreateLogger <Program>(); logger.LogError(ex, "An error occurred seeding the DB."); } } host.Run(); }
public TurmaParticipanteRepository(DbContextSeed ctx, CurrentUser user) : base(ctx) { this._user = user; }
public ManySampleTypeRepository(DbContextSeed ctx, CurrentUser user) : base(ctx) { this._user = user; }
public SampleItemRepository(DbContextSeed ctx, CurrentUser user) : base(ctx) { this._user = user; }
public CodigoVerificacaoRepository(DbContextSeed ctx, CurrentUser user) : base(ctx) { this._user = user; }
protected override async void ConfigureWebHost(IWebHostBuilder builder) { ClientOptions.BaseAddress = new Uri("https://localhost:44316/"); builder.UseEnvironment("Test"); builder.UseUrls("https://localhost:44316/"); builder.ConfigureServices(services => { // Create a new service provider. var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); // Add a database context(ApplicationDbContext) using an in-memory // database for testing. services.AddDbContext <ShoppingDBContext>(options => { options.UseInMemoryDatabase("InMemoryDbForTesting"); options.UseInternalServiceProvider(serviceProvider); }); // Build the service provider. var sp = services.BuildServiceProvider(); services.Configure <ClientConfigurationModel>(new ConfigurationBuilder().Build()); // Create a scope to obtain a reference to the database using (var scope = sp.CreateScope()) { var scopedServices = scope.ServiceProvider; var db = scopedServices.GetRequiredService <ShoppingDBContext>(); // Ensure the database is created. db.Database.EnsureCreated(); // Seed the database with test data. DbContextSeed.SeedAsync(db).Wait(); } }); }
public UsuarioRepository(DbContextSeed ctx, CurrentUser user) : base(ctx) { this._user = user; }
public ProductRepository(DbContextSeed ctx, CurrentUser user) : base(ctx) { this._user = user; }
public void Run() { DbContextSeed.InitUsers(_userManager); DbContextSeed.InitMenuTree(_systemIdentityDbContext); }
public ResourceRepository(DbContextSeed ctx, CurrentUser user) : base(ctx) { this._user = user; }
public StatusRegisterRepository(DbContextSeed ctx, CurrentUser user) : base(ctx) { this._user = user; }
public StatusDaTurmaRepository(DbContextSeed ctx, CurrentUser user) : base(ctx) { this._user = user; }
public TesteRepository(DbContextSeed ctx) : base(ctx) { }