Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 

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