您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

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