You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

27 lines
1.2 KiB

  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.EntityFrameworkCore;
  3. using Microsoft.Extensions.DependencyInjection;
  4. namespace Cap.Consistency.EntityFrameworkCore.Test
  5. {
  6. public static class DbUtil
  7. {
  8. public static IServiceCollection ConfigureDbServices(string connectionString, IServiceCollection services = null) {
  9. return ConfigureDbServices<ConsistencyDbContext>(connectionString, services);
  10. }
  11. public static IServiceCollection ConfigureDbServices<TContext>(string connectionString, IServiceCollection services = null) where TContext : DbContext {
  12. if (services == null) {
  13. services = new ServiceCollection();
  14. }
  15. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  16. services.AddDbContext<TContext>(options => options.UseSqlServer(connectionString));
  17. return services;
  18. }
  19. public static TContext Create<TContext>(string connectionString) where TContext : DbContext {
  20. var serviceProvider = ConfigureDbServices<TContext>(connectionString).BuildServiceProvider();
  21. return serviceProvider.GetRequiredService<TContext>();
  22. }
  23. }
  24. }