50 lines
1.4 KiB
C#
50 lines
1.4 KiB
C#
using back.Options;
|
|
using back.persistance.data;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace back.ServicesExtensions;
|
|
|
|
public static partial class ServicesExtensions
|
|
{
|
|
private static IServiceCollection AddDatabaseContext(this IServiceCollection services)
|
|
{
|
|
services.AddContext<DataContext>();
|
|
|
|
return services;
|
|
}
|
|
private static IServiceCollection AddContext<T>(this IServiceCollection services)
|
|
where T : DbContext
|
|
{
|
|
var config = services
|
|
.BuildServiceProvider()
|
|
.GetRequiredService<IOptionsSnapshot<DatabaseConfig>>()
|
|
.Get(DatabaseConfig.DataStorage);
|
|
|
|
services.AddDbContext<T>(options =>
|
|
{
|
|
options.UseDatabaseConfig(config);
|
|
});
|
|
|
|
using var scope = services.BuildServiceProvider().CreateScope();
|
|
var context = scope.ServiceProvider
|
|
.GetRequiredService<T>();
|
|
var isDevelopment = scope.ServiceProvider
|
|
.GetRequiredService<IHostEnvironment>()
|
|
.IsDevelopment();
|
|
|
|
if (isDevelopment && !context.Database.HasPendingModelChanges())
|
|
{
|
|
context.Database.EnsureCreated();
|
|
}
|
|
else
|
|
{
|
|
context.Database.EnsureCreated();
|
|
context.Database.Migrate();
|
|
}
|
|
context.SaveChanges();
|
|
|
|
return services;
|
|
}
|
|
}
|