fix: подключение к бд

This commit is contained in:
mfnefd 2024-11-25 20:56:39 +04:00
parent e8a6cc2b17
commit 7f30d20c73
10 changed files with 175 additions and 27 deletions

View File

@ -1,6 +1,5 @@
@Controllers_HostAddress = http://localhost:5125
GET {{Controllers_HostAddress}}/weatherforecast/
Accept: application/json
###

View File

@ -1,19 +0,0 @@
using Infrastructure;
using Microsoft.EntityFrameworkCore;
namespace Controllers.Extensions;
public static class DbConnectionServiceExtension
{
public static void AddDbConnectionService(this IServiceCollection services)
{
var host = Environment.GetEnvironmentVariable("DB_HOST");
var database = Environment.GetEnvironmentVariable("DB_NAME");
var username = Environment.GetEnvironmentVariable("DB_USER");
var password = Environment.GetEnvironmentVariable("DB_PASSWORD");
var connectionString = $"Host={host};Database={database};Username={username};Password={password}";
services.AddDbContext<DatabaseContext>(options => options.UseNpgsql(connectionString));
services.AddSingleton<IDbContextFactory<DatabaseContext>, DbContextFactory>();
}
}

View File

@ -7,7 +7,7 @@ public static class AddDomainServicesExtension
{
public static void AddDomainServices(this IServiceCollection services)
{
services.AddSingleton<IAuthService, AuthService>();
services.AddSingleton<IUserService, UserService>();
services.AddTransient<IAuthService, AuthService>();
services.AddTransient<IUserService, UserService>();
}
}

View File

@ -9,6 +9,6 @@ public static class AddReposExtension
{
public static void AddRepos(this IServiceCollection services)
{
services.AddSingleton<IUserRepo, UserRepo>();
services.AddTransient<IUserRepo, UserRepo>();
}
}

View File

@ -0,0 +1,29 @@
using Infrastructure;
using Microsoft.EntityFrameworkCore;
namespace Controllers.Extensions;
public static class DatabaseSetupExtension
{
public static void AddDbConnectionService(this IServiceCollection services, IConfiguration config)
{
var connectionString = config.GetConnectionString("DefaultConnection")
?? throw new ArgumentException("Нет строки подключения");
services.AddDbContext<DatabaseContext>(options => options.UseNpgsql(connectionString));
services.AddSingleton<IDbContextFactory<DatabaseContext>, DbContextFactory>();
}
public static void MigrateDb(this IApplicationBuilder app)
{
try
{
using var scope = app.ApplicationServices.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<DatabaseContext>();
context.Database.Migrate();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

View File

@ -3,9 +3,9 @@ using Controllers.Extensions;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddDbConnectionService(builder.Configuration);
builder.Services.AddRepos();
builder.Services.AddDomainServices();
builder.Services.AddDbConnectionService();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
@ -21,10 +21,12 @@ if (app.Environment.IsDevelopment())
app.UseSwaggerUI();
}
app.MigrateDb();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
await app.RunAsync();

View File

@ -0,0 +1,52 @@
// <auto-generated />
using System;
using Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Infrastructure.Migrations
{
[DbContext(typeof(DatabaseContext))]
[Migration("20241125164748_User")]
partial class User
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Infrastructure.Models.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<decimal>("Balance")
.HasColumnType("numeric");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Users");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,36 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Infrastructure.Migrations
{
/// <inheritdoc />
public partial class User : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
Password = table.Column<string>(type: "text", nullable: false),
Balance = table.Column<decimal>(type: "numeric", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Users");
}
}
}

View File

@ -0,0 +1,49 @@
// <auto-generated />
using System;
using Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Infrastructure.Migrations
{
[DbContext(typeof(DatabaseContext))]
partial class DatabaseContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Infrastructure.Models.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<decimal>("Balance")
.HasColumnType("numeric");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Users");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -8,9 +8,9 @@ namespace Infrastructure.Repositories;
public class UserRepo : IUserRepo
{
public readonly DbContextFactory _factory;
public readonly IDbContextFactory<DatabaseContext> _factory;
public UserRepo(DbContextFactory factory)
public UserRepo(IDbContextFactory<DatabaseContext> factory)
{
_factory = factory;
}