Skip to content
This repository has been archived by the owner on Nov 18, 2020. It is now read-only.

Commit

Permalink
Вынес переменные для подключения к БД в environment.json. Сделал подг…
Browse files Browse the repository at this point in the history
…рузку этих переменных на старте приложения. Попытка установить dotnet-fm и накатывать миграции (пока неудачно)
  • Loading branch information
nzour committed Jul 17, 2019
1 parent 37de907 commit 4e41af0
Show file tree
Hide file tree
Showing 62 changed files with 6,658 additions and 1,369 deletions.
2 changes: 2 additions & 0 deletions .idea/.idea.backend.dir/.idea/contentModel.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

754 changes: 370 additions & 384 deletions .idea/.idea.backend.dir/.idea/workspace.xml

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions docker/core/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@ FROM mcr.microsoft.com/dotnet/core/sdk:2.2

WORKDIR /app

# Cli для миграций
RUN dotnet tool install -g FluentMigrator.DotNet.Cli

CMD ["dotnet", "run"]
4 changes: 2 additions & 2 deletions src/Application/Http/Token/TokenController.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using app.Infrastructure.NHibernate;
using Microsoft.AspNetCore.Mvc;

namespace app.Application.Http.Token
Expand All @@ -10,8 +11,7 @@ public class TokenController : Controller
public JsonResult Index()
{
var foo = new Foo();

return Json("Ok!");
return Json(DbAccessor.ConnectionString);
}
}
}
38 changes: 38 additions & 0 deletions src/DependencyInjection/Kernel.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using app.DependencyInjection.ServiceRecorder;
using app.Infrastructure.NHibernate;
using FluentMigrator.Runner;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;

namespace app.DependencyInjection
{
Expand All @@ -10,9 +15,16 @@ namespace app.DependencyInjection
/// </summary>
public class Kernel : AbstractAssemblyAware
{
/// <summary>
/// По дефолту, файл с переменными окружения.
/// </summary>
private const string EnvFile = "environment.json";

public static void Boot(IServiceCollection services)
{
RegisterEnvironment();
RecordServices(services);
RegisterMigrations(services);
}

/// <summary>
Expand All @@ -30,5 +42,31 @@ private static void RecordServices(IServiceCollection services)
.Invoke(Activator.CreateInstance(recorder), new object[] { services });
}
}

/// <summary>
/// Регистрирует все перменные окружения из файла environment.json (по-умолчанию).
/// </summary>
private static void RegisterEnvironment()
{
using (var reader = new StreamReader(EnvFile))
{
var json = JsonConvert.DeserializeObject<Dictionary<string, string>>(reader.ReadToEnd());

foreach (var (key, value) in json)
{
Environment.SetEnvironmentVariable(key, value);
}
}
}

private static void RegisterMigrations(IServiceCollection services)
{
services.AddFluentMigratorCore()
.ConfigureRunner(runner => runner
.AddPostgres()
.WithGlobalConnectionString(DbAccessor.ConnectionString)
.ScanIn(GetAssembly()).For.Migrations())
.AddLogging(logBuilder => logBuilder.AddFluentMigratorConsole());
}
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using app.Common.Annotation;
using app.Infrastructure.NHibernate.Repository;
using FluentNHibernate.Conventions;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens.Saml;

namespace app.DependencyInjection.ServiceRecorder.InjectedAttributeRecorder
{
Expand All @@ -23,7 +19,7 @@ private IEnumerable<TypeInfo> FindClasses()
{
return GetAssembly()
.DefinedTypes
.Where(type => { return !type.IsInterface && GetFieldsWithInjected(type).IsNotEmpty(); });
.Where(type => !type.IsInterface && GetPropertiesWithInjectedAttribute(type).IsNotEmpty());
}

/// <summary>
Expand All @@ -34,7 +30,7 @@ private void TryInjectServices(IEnumerable<TypeInfo> classes, IServiceProvider p
{
foreach (var @class in classes)
{
var properties = GetFieldsWithInjected(@class);
var properties = GetPropertiesWithInjectedAttribute(@class);

foreach (var property in properties)
{
Expand All @@ -54,9 +50,9 @@ private void InjectProperty(object @class, PropertyInfo property, IServiceProvid
try
{
var propertyType = property.PropertyType;
var service = provider.GetService(propertyType) ?? Activator.CreateInstance(propertyType);
// It doesn't work. Idk
// property.SetValue(@class, service);
//var service = provider.GetService(propertyType) ?? Activator.CreateInstance(propertyType);
// todo: Not working. Fix in future.
// property.SetValue(@class, service);
}
catch (Exception e)
{
Expand All @@ -71,10 +67,10 @@ private void InjectProperty(object @class, PropertyInfo property, IServiceProvid
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private IEnumerable<PropertyInfo> GetFieldsWithInjected(TypeInfo type)
private IEnumerable<PropertyInfo> GetPropertiesWithInjectedAttribute(TypeInfo type)
{
return type.GetRuntimeProperties()
.Where(field => field.GetCustomAttributes().Contains(new InjectedAttribute()));
.Where(prop => prop.GetCustomAttributes().Contains(new InjectedAttribute()));
}

protected override IEnumerable<AbstractServiceRecorder> GetDependencies()
Expand Down
26 changes: 26 additions & 0 deletions src/Infrastructure/NHibernate/DbAccessor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System;

namespace app.Infrastructure.NHibernate
{
/// <summary>
/// Класс, знающий о данных для подключения к БД.
/// Данные задаются в файле environment.json (по умолчанию)
/// </summary>
public static class DbAccessor
{
// Хост базы данных
public static string Host { get; } = Environment.GetEnvironmentVariable("DB_HOST");

// Имя базы данных
public static string Database { get; } = Environment.GetEnvironmentVariable("DB_NAME");

// Пользовать
public static string User { get; } = Environment.GetEnvironmentVariable("DB_USER");

// Пароль
public static string Password { get; } = Environment.GetEnvironmentVariable("DB_PASSWORD");

// Готовая страка для connecion к БД.
public static string ConnectionString { get; } = $"Server={Host};Port=5432;Database={Database};User Id={User};Password={Password};";
}
}
9 changes: 3 additions & 6 deletions src/Infrastructure/NHibernate/NHibernateHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Tool.hbm2ddl;

namespace app.Infrastructure.NHibernate
{
Expand All @@ -28,14 +26,13 @@ private static ISessionFactory SessionFactory
.PostgreSQL82
//Понятия не имею что это и для чего. Но без этого не работает ¯\_(ツ)_/¯
.Raw("hbm2ddl.keywords", "none")
.ConnectionString(
"Server=localhost;Port=5432;Database=zobor;User Id=root;Password=root;"));
.ConnectionString(DbAccessor.ConnectionString));

RegisterEntitiesRecursively(fluentConfiguration, typeof(AbstractEntity));

_sessionFactory = fluentConfiguration
.ExposeConfiguration(cfg => new SchemaUpdate(cfg)
.Execute(false, true))
// .ExposeConfiguration(cfg => new SchemaUpdate(cfg)
// .Execute(false, true))
.BuildSessionFactory();
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/app.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentMigrator" Version="3.2.1" />
<PackageReference Include="FluentMigrator.Console" Version="3.2.1" />
<PackageReference Include="FluentMigrator.Generator" Version="1.0.5" />
<PackageReference Include="FluentMigrator.Runner" Version="3.2.1" />
<PackageReference Include="FluentMigrator.Runner.Core" Version="3.2.1" />
<PackageReference Include="FluentMigrator.Runner.Postgres" Version="3.2.1" />
<PackageReference Include="FluentMigrator.Tools" Version="3.2.1" />
<PackageReference Include="FluentNHibernate" Version="2.1.2" />
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
Expand Down
16 changes: 8 additions & 8 deletions src/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
12 changes: 2 additions & 10 deletions src/bin/Debug/netcoreapp2.2/app.deps.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"runtimeTarget": {
"name": ".NETCoreApp,Version=v2.2",
"signature": "ae7c2cd254d45d86da10df44ece48b4b82c411e7"
"signature": "965cccb0f4eaf6579b8894c2090c598e8042a864"
},
"compilationOptions": {
"defines": [
Expand All @@ -24,12 +24,12 @@
".NETCoreApp,Version=v2.2": {
"app/1.0.0": {
"dependencies": {
"FluentMigrator": "3.2.1",
"FluentMigrator.Console": "3.2.1",
"FluentMigrator.Generator": "1.0.5",
"FluentMigrator.Runner": "3.2.1",
"FluentMigrator.Runner.Core": "3.2.1",
"FluentMigrator.Runner.Postgres": "3.2.1",
"FluentMigrator.Tools": "3.2.1",
"FluentNHibernate": "2.1.2",
"Microsoft.AspNetCore.App": "2.2.0",
"Microsoft.AspNetCore.Razor.Design": "2.2.0",
Expand Down Expand Up @@ -354,7 +354,6 @@
"lib/netstandard2.0/System.Data.SqlServerCe.dll": {}
}
},
"FluentMigrator.Tools/3.2.1": {},
"FluentNHibernate/2.1.2": {
"dependencies": {
"NHibernate": "5.2.5"
Expand Down Expand Up @@ -3820,13 +3819,6 @@
"path": "fluentmigrator.runner.sqlserverce/3.2.1",
"hashPath": "fluentmigrator.runner.sqlserverce.3.2.1.nupkg.sha512"
},
"FluentMigrator.Tools/3.2.1": {
"type": "package",
"serviceable": true,
"sha512": "sha512-UKbhx7uhGFRrt1BBIKTkMVbKlGjEkoufCwpbeP2Pe9LjTYW3olKtaIriGUhZ4K0IGiGZsWIdUwneNiJ+6gzvZQ==",
"path": "fluentmigrator.tools/3.2.1",
"hashPath": "fluentmigrator.tools.3.2.1.nupkg.sha512"
},
"FluentNHibernate/2.1.2": {
"type": "package",
"serviceable": true,
Expand Down
Binary file modified src/bin/Debug/netcoreapp2.2/app.dll
Binary file not shown.
Binary file modified src/bin/Debug/netcoreapp2.2/app.pdb
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file added src/bin/Debug/netcoreapp2.2/publish/Npgsql.dll
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loading

0 comments on commit 4e41af0

Please sign in to comment.