Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 

27 rader
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. }