Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move application and service configuration to Extension classes to cleanup Program.cs #7

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ bld/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/

# Jetbrains IDEs
.idea/

# Visual Studio 2017 auto generated files
Generated\ Files/

Expand Down
2 changes: 1 addition & 1 deletion DidactEngine/Licensing/LicenseValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public bool ValidateLicense(string fullLicense)

// Parse the license data
var licenseData = Encoding.UTF8.GetString(dataBytes);
var parts = licenseData.Split('|');
var licenseParts = licenseData.Split('|');
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@DMiradakis This was giving me build errors so I changed the variable name.

var failSafeExpiry = DateTime.Parse(parts[1]);

// Check if the fail-safe expiry is still valid
Expand Down
120 changes: 11 additions & 109 deletions DidactEngine/Program.cs
Original file line number Diff line number Diff line change
@@ -1,117 +1,19 @@
using DidactEngine.Services.BackgroundServices;
using DidactEngine.Services.Contexts;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.OpenApi.Models;
using System.Reflection;
using DidactCore.Flows;
using DidactEngine.Services.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "DevelopmentCORS",
policy =>
{
policy.WithOrigins("http://localhost:8080");
policy.AllowAnyMethod();
policy.AllowAnyHeader();
policy.AllowCredentials();
});
});

#region Configure DbContext and Gateway.

var connStringFactory = (string name) => new SqlConnectionStringBuilder(
builder.Configuration.GetConnectionString(name))
{
ApplicationName = "Didact",
PersistSecurityInfo = true,
MultipleActiveResultSets = true,
WorkstationID = Environment.MachineName,
TrustServerCertificate = true
}.ConnectionString;

builder.Services.AddDbContext<DidactDbContext>(
(sp, opt) =>
{
opt.UseMemoryCache(sp.GetRequiredService<IMemoryCache>());
opt.UseSqlServer(connStringFactory("Didact"), opt => opt.CommandTimeout(110));
if (builder.Configuration.GetValue<bool?>("EnableSensitiveDataLogging").GetValueOrDefault())
{
opt.EnableDetailedErrors();
opt.EnableSensitiveDataLogging();
}
});

#endregion Configure DbContext and Gateway.

builder.Services.AddControllers();
builder.Services.AddMemoryCache();

// Register Swagger
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
string swaggerVersion = "v1";
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc(swaggerVersion, new OpenApiInfo
{
Version = swaggerVersion,
Title = "Didact REST API",
Description = "The central REST API of the Didact Engine."
});

var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
builder.Services.AddEndpointsApiExplorer();

// Register BackgroundServices
builder.Services.AddHostedService<WorkerBackgroundService>();
// Register Flow helper services from DidactCore.
//builder.Services.AddSingleton<IFlowExecutor, FlowExecutor>();
// Register repositories from DidactCore.
//builder.Services.AddScoped<IFlowRepository>();
// Configure Engine
builder.ConfigureCors();
builder.ConfigureOpenApi();
builder.ConfigureDatabase();
builder.ConfigureApplicationServices();

// Build Engine
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseCors("DevelopmentCORS");
}

app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

var logger = app.Services.GetRequiredService<ILogger<Program>>();

try
{
using (var scope = app.Services.CreateScope())
using (var dbContext = scope.ServiceProvider.GetRequiredService<DidactDbContext>())
try
{
logger.LogInformation("Attempting to migrate the database on engine startup...");
dbContext.Database.Migrate();
logger.LogInformation("Database migrated successfully.");
}
catch (Exception ex)
{
logger.LogError(ex, "Unhandled exception while applying migrations for {T}", typeof(DidactDbContext));
throw;
}
// Configure middleware
app.ConfigureMiddleware();

app.Run();
return 0;
}
catch (Exception ex)
{
logger.LogCritical(ex, "An unhandled exception occurred during bootstrapping");
return 1;
}
// Run Engine
await app.StartEngine<DidactDbContext>();
20 changes: 20 additions & 0 deletions DidactEngine/Services/Extensions/CorsExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
namespace DidactEngine.Services.Extensions
{
public static class CorsExtensions
{
public static void ConfigureCors(this IHostApplicationBuilder builder)
{
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "DevelopmentCORS",
policy =>
{
policy.WithOrigins("http://localhost:8080");
policy.AllowAnyMethod();
policy.AllowAnyHeader();
policy.AllowCredentials();
});
});
}
}
}
34 changes: 34 additions & 0 deletions DidactEngine/Services/Extensions/DbConfigurationExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using DidactEngine.Services.Contexts;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;

namespace DidactEngine.Services.Extensions
{
public static class DbConfigurationExtensions
{
public static void ConfigureDatabase(this IHostApplicationBuilder builder)
{
string connStringFactory(string name) => new SqlConnectionStringBuilder(builder.Configuration.GetConnectionString(name))
{
ApplicationName = "Didact",
PersistSecurityInfo = true,
MultipleActiveResultSets = true,
WorkstationID = Environment.MachineName,
TrustServerCertificate = true
}.ConnectionString;

builder.Services.AddDbContext<DidactDbContext>(
(sp, opt) =>
{
opt.UseMemoryCache(sp.GetRequiredService<IMemoryCache>());
opt.UseSqlServer(connStringFactory("Didact"), opt => opt.CommandTimeout(110));
if (builder.Configuration.GetValue<bool?>("EnableSensitiveDataLogging").GetValueOrDefault())
{
opt.EnableDetailedErrors();
opt.EnableSensitiveDataLogging();
}
});
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
namespace DidactEngine.Services.Extensions
{
public static class MiddlewareConfigurationExtensions
{
public static void ConfigureMiddleware(this WebApplication app)
{
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseCors("DevelopmentCORS");
}

app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
}
}
}
41 changes: 24 additions & 17 deletions DidactEngine/Services/Extensions/MigrationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,34 @@ namespace DidactEngine.Services.Extensions
{
public static class MigrationExtensions
{
public static WebApplication MigrateDatabase<T>(this WebApplication webApp)
where T : DbContext
public static async Task StartEngine<T>(this IHost app) where T : DbContext
{
using (var scope = webApp.Services.CreateScope())
using (var dbContext = scope.ServiceProvider.GetRequiredService<T>())
try
{
dbContext.Database.Migrate();
}
catch (Exception e)
{
scope.ServiceProvider
.GetRequiredService<ILogger<T>>()
.LogError(e, "Unhandled exception while applying migrations for {T}", typeof(T));
var logger = app.Services.GetRequiredService<ILogger<T>>();

Console.WriteLine(e);
try
{
using (var scope = app.Services.CreateScope())
using (var dbContext = scope.ServiceProvider.GetRequiredService<T>())

throw;
}
try
{
logger.LogInformation("Attempting to migrate the database on engine startup...");
await dbContext.Database.MigrateAsync();
logger.LogInformation("Database migrated successfully.");
}
catch (Exception ex)
{
logger.LogError(ex, "Unhandled exception while applying migrations for {T}", typeof(T));
throw;
}

return webApp;
app.Run();
}
catch (Exception ex)
{
logger.LogCritical(ex, "An unhandled exception occurred during bootstrapping");
await app.StopAsync();
}
}
}
}
26 changes: 26 additions & 0 deletions DidactEngine/Services/Extensions/OpenApiExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using Microsoft.OpenApi.Models;
using System.Reflection;

namespace DidactEngine.Services.Extensions
{
public static class OpenApiExtensions
{
public static void ConfigureOpenApi(this IHostApplicationBuilder builder)
{
string swaggerVersion = "v1";
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc(swaggerVersion, new OpenApiInfo
{
Version = swaggerVersion,
Title = "Didact REST API",
Description = "The central REST API of the Didact Engine."
});

var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
builder.Services.AddEndpointsApiExplorer();
}
}
}
20 changes: 20 additions & 0 deletions DidactEngine/Services/Extensions/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using DidactEngine.Services.BackgroundServices;

namespace DidactEngine.Services.Extensions
{
public static class ServiceCollectionExtensions
{
public static void ConfigureApplicationServices(this IHostApplicationBuilder builder)
{
builder.Services.AddControllers();
builder.Services.AddMemoryCache();

// Register BackgroundServices
builder.Services.AddHostedService<WorkerBackgroundService>();
// Register Flow helper services from DidactCore.
//builder.Services.AddSingleton<IFlowExecutor, FlowExecutor>();
// Register repositories from DidactCore.
//builder.Services.AddScoped<IFlowRepository>();
}
}
}