84 lines
2.6 KiB
C#
84 lines
2.6 KiB
C#
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Serilog;
|
|
using StockDBEF.Models;
|
|
using System;
|
|
using System.IO;
|
|
using System.Threading.Tasks;
|
|
using System.Threading;
|
|
|
|
// DI, SeriLog, Settings
|
|
|
|
namespace StockDBEF
|
|
{
|
|
class Program
|
|
{
|
|
static void Main(string[] args)
|
|
{
|
|
var builder = new ConfigurationBuilder();
|
|
BuildConfig(builder);
|
|
|
|
Log.Logger = new LoggerConfiguration()
|
|
.ReadFrom.Configuration(builder.Build())
|
|
.Enrich.FromLogContext()
|
|
.WriteTo.Console()
|
|
.CreateLogger();
|
|
|
|
Log.Logger.Information("Application starting");
|
|
|
|
var host = Host.CreateDefaultBuilder()
|
|
.ConfigureServices((context, services) =>
|
|
{
|
|
services.AddEntityFrameworkSqlite();
|
|
services.AddHostedService<DatabaseStartup>();
|
|
//services.AddDbContext<StockDBContext>();
|
|
services.AddDbContextPool<StockDBContext>(o =>
|
|
{
|
|
o.UseSqlite("Data Source=Stocks.db");
|
|
});
|
|
|
|
services.AddTransient<IGreetingService, GreetingService>();
|
|
})
|
|
.UseSerilog()
|
|
.Build();
|
|
|
|
var svc = ActivatorUtilities.CreateInstance<GreetingService>(host.Services);
|
|
svc.Run();
|
|
}
|
|
|
|
static void BuildConfig(IConfigurationBuilder builder)
|
|
{
|
|
builder.SetBasePath(Directory.GetCurrentDirectory())
|
|
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
|
|
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
|
|
.AddEnvironmentVariables();
|
|
}
|
|
|
|
|
|
}
|
|
|
|
public class DatabaseStartup : IHostedService
|
|
{
|
|
private readonly IServiceProvider serviceProvider;
|
|
public DatabaseStartup(IServiceProvider serviceProvider)
|
|
{
|
|
this.serviceProvider = serviceProvider;
|
|
}
|
|
|
|
public async Task StartAsync(CancellationToken cancellationToken)
|
|
{
|
|
using (var scope = serviceProvider.CreateScope())
|
|
{
|
|
var db = scope.ServiceProvider.GetRequiredService<StockDBContext>();
|
|
await db.Database.EnsureCreated();
|
|
// or
|
|
await db.Database.MigrateAsync();
|
|
}
|
|
}
|
|
|
|
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
|
}
|
|
|
|
}
|