Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.96 KB | None | 0 0
  1. using efcore_tenancy.Data;
  2. using Microsoft.EntityFrameworkCore;
  3. using Microsoft.EntityFrameworkCore.Diagnostics;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.Extensions.DependencyInjection;
  6.  
  7. namespace efcore_tenancy.Infrastructure
  8. {
  9. public static class ServiceCollectionExtensions
  10. {
  11. public static IServiceCollection UseDiscriminatorColumn(this IServiceCollection services, IConfiguration configuration)
  12. => services.UseEFInterceptor<DiscriminatorColumnInterceptor>(configuration);
  13.  
  14. public static IServiceCollection UseSchemaPerTenant(this IServiceCollection services, IConfiguration configuration)
  15. => services.UseEFInterceptor<SchemaInterceptor>(configuration);
  16.  
  17. public static IServiceCollection UseDatabasePerTenant(this IServiceCollection services, IConfiguration configuration)
  18. => services.UseEFInterceptor<DatabaseInterceptor>(configuration);
  19.  
  20. private static IServiceCollection UseEFInterceptor<T>(this IServiceCollection services, IConfiguration configuration)
  21. where T : class, IInterceptor
  22. {
  23. return services
  24. .AddScoped<DbContextOptions>((serviceProvider) =>
  25. {
  26. var tenant = serviceProvider.GetRequiredService<TenantInfo>();
  27.  
  28. var efServices = new ServiceCollection();
  29. efServices.AddEntityFrameworkSqlServer();
  30. efServices.AddScoped<TenantInfo>(s =>
  31. serviceProvider.GetRequiredService<TenantInfo>()); // Allows DI for tenant info, set by parent pipeline via middleware
  32. efServices.AddScoped<IInterceptor, T>(); // Adds the interceptor
  33.  
  34. var connectionString = configuration.GetConnectionString("SqlServerConnection");
  35.  
  36. return new DbContextOptionsBuilder<ProductsDbContext>()
  37. .UseInternalServiceProvider(efServices.BuildServiceProvider())
  38. .UseSqlServer(connectionString)
  39. .Options;
  40. })
  41. .AddScoped<ProductsDbContext>(s => new ProductsDbContext(s.GetRequiredService<DbContextOptions>()));
  42. }
  43.  
  44. public static IServiceCollection UseConnectionPerTenant(this IServiceCollection services, IConfiguration configuration)
  45. {
  46. services.AddScoped<ProductsDbContext>((serviceProvider) =>
  47. {
  48. var tenant = serviceProvider.GetRequiredService<TenantInfo>(); // Get from parent service provider (ASP.NET MVC Pipeline)
  49. var connectionString = configuration.GetConnectionString(tenant.Name);
  50. var options = new DbContextOptionsBuilder<ProductsDbContext>()
  51. .UseSqlServer(connectionString)
  52. .Options;
  53. var context = new ProductsDbContext(options);
  54. return context;
  55. });
  56.  
  57. return services;
  58. }
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement