Skip to content
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
1 change: 0 additions & 1 deletion module.ignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ Microsoft.AspNetCore.SignalR.Client.Core.dll
Microsoft.AspNetCore.SignalR.Client.dll
Microsoft.AspNetCore.SignalR.Protocols.NewtonsoftJson.dll
Microsoft.AspNetCore.SignalR.StackExchangeRedis.dll
Microsoft.Azure.AppConfiguration.AspNetCore.dll
Microsoft.Azure.SignalR.Common.dll
Microsoft.Azure.SignalR.dll
Microsoft.Azure.SignalR.Protocols.dll
Expand Down
59 changes: 59 additions & 0 deletions src/VirtoCommerce.Platform.Core/Modularity/IPlatformStartup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace VirtoCommerce.Platform.Core.Modularity
{
/// <summary>
/// Allows modules to participate in early platform startup phases that occur
/// before or outside the standard <see cref="IModule.Initialize"/>/<see cref="IModule.PostInitialize"/> lifecycle.
/// <para>
/// Implementations must have a parameterless constructor (instantiated via <see cref="System.Activator.CreateInstance(System.Type)"/>).
/// </para>
/// <para>
/// Declare the implementation type in <c>module.manifest</c> using the <c>&lt;startupType&gt;</c> element.
/// </para>
/// </summary>
public interface IPlatformStartup
{
/// <summary>
/// Controls the order in which startup types are invoked within the same phase.
/// Lower values run first. Use <see cref="StartupPriority"/> constants for well-known values.
/// </summary>
int Priority => StartupPriority.Default;

/// <summary>
/// Determines when <see cref="Configure"/> is called in the middleware pipeline.
/// </summary>
PipelinePhase Phase => PipelinePhase.Initialization;

/// <summary>
/// Called during host building (Program.cs ConfigureAppConfiguration phase).
/// Use this to add configuration sources (e.g., Azure App Configuration).
/// </summary>
/// <param name="builder">The configuration builder to add sources to.</param>
/// <param name="hostEnvironment">The host environment (provides EnvironmentName, ContentRootPath, etc.).</param>
void ConfigureAppConfiguration(IConfigurationBuilder builder, IHostEnvironment hostEnvironment) { }

/// <summary>
/// Called during host building (Program.cs ConfigureServices phase).
/// Use this to register hosted services (e.g., Hangfire server).
/// </summary>
/// <param name="services">The host-level service collection.</param>
/// <param name="configuration">The fully-built host configuration.</param>
void ConfigureHostServices(IServiceCollection services, IConfiguration configuration) { }

/// <summary>
/// Called during Startup.ConfigureServices, after modules are loaded via AddModules().
/// Use this to register application-level services.
/// </summary>
void ConfigureServices(IServiceCollection services, IConfiguration configuration) { }

/// <summary>
/// Called during Startup.Configure at the pipeline position determined by <see cref="Phase"/>.
/// Use this to add middleware or perform initialization.
/// </summary>
void Configure(IApplicationBuilder app, IConfiguration configuration) { }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ public ManifestModuleInfo()

public ICollection<ManifestAppInfo> Apps { get; } = new List<ManifestAppInfo>();

public string StartupType { get; private set; }

public virtual ManifestModuleInfo LoadFromManifest(ModuleManifest manifest)
{
if (manifest == null)
Expand Down Expand Up @@ -93,6 +95,7 @@ public virtual ManifestModuleInfo LoadFromManifest(ModuleManifest manifest)
Tags = manifest.Tags;
Identity = new ModuleIdentity(Id, Version, Optional);
ModuleType = manifest.ModuleType;
StartupType = manifest.StartupType;

if (manifest.Groups != null)
{
Expand Down
3 changes: 3 additions & 0 deletions src/VirtoCommerce.Platform.Core/Modularity/ModuleManifest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ public class ModuleManifest
[XmlElement("moduleType")]
public string ModuleType { get; set; }

[XmlElement("startupType")]
public string StartupType { get; set; }

[XmlArray("dependencies")]
[XmlArrayItem("dependency")]
public ManifestDependency[] Dependencies { get; set; }
Expand Down
28 changes: 28 additions & 0 deletions src/VirtoCommerce.Platform.Core/Modularity/PipelinePhase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
namespace VirtoCommerce.Platform.Core.Modularity
{
/// <summary>
/// Determines when an <see cref="IPlatformStartup.Configure"/> method is invoked
/// within the Startup.Configure pipeline.
/// </summary>
public enum PipelinePhase
{
/// <summary>
/// Before routing and authentication middleware.
/// Use for configuration refresh middleware, custom request preprocessing, etc.
/// </summary>
EarlyMiddleware = 0,

/// <summary>
/// Within the ExecuteSynchronized block, after platform migrations
/// but before IModule.PostInitialize.
/// Use for infrastructure that requires the database to be ready (e.g., Hangfire).
/// </summary>
Initialization = 1,

/// <summary>
/// After endpoints are mapped and modules are post-initialized.
/// Use for middleware that needs to see all endpoints (e.g., Swagger).
/// </summary>
LateMiddleware = 2
}
}
21 changes: 21 additions & 0 deletions src/VirtoCommerce.Platform.Core/Modularity/StartupPriority.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
namespace VirtoCommerce.Platform.Core.Modularity
{
/// <summary>
/// Well-known priority values for <see cref="IPlatformStartup"/> ordering.
/// Lower values execute first.
/// </summary>
public static class StartupPriority
{
/// <summary>Configuration sources should load first (e.g., Azure App Configuration).</summary>
public const int ConfigurationSource = -1000;

/// <summary>Infrastructure services like logging and caching (e.g., Serilog).</summary>
public const int Infrastructure = -500;

/// <summary>Default priority for module startup types.</summary>
public const int Default = 0;

/// <summary>Services that depend on other modules being registered (e.g., Swagger).</summary>
public const int Late = 500;
}
}
124 changes: 124 additions & 0 deletions src/VirtoCommerce.Platform.Modules/PlatformStartupDiscovery.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using VirtoCommerce.Platform.Core.Modularity;

namespace VirtoCommerce.Platform.Modules
{
/// <summary>
/// Discovers and instantiates <see cref="IPlatformStartup"/> implementations from module assemblies.
/// Designed to run early in the platform lifecycle (Program.cs level) before DI is configured.
/// </summary>
public static class PlatformStartupDiscovery
{
/// <summary>
/// Scans module manifests in the discovery path for those declaring a startupType,
/// loads their assemblies from the probing path, and instantiates the startup types.
/// Returns an empty list if paths are missing or no startup types are found.
/// </summary>
/// <param name="discoveryPath">Path to scan for module.manifest files (e.g., "modules/").</param>
/// <param name="probingPath">Path where module assemblies are located (e.g., "app_data/modules/").</param>
/// <returns>List of discovered startup instances ordered by <see cref="IPlatformStartup.Priority"/>.</returns>
public static IReadOnlyList<IPlatformStartup> DiscoverStartups(string discoveryPath, string probingPath)
{
var startups = new List<IPlatformStartup>();

if (string.IsNullOrEmpty(discoveryPath) || !Directory.Exists(discoveryPath))
{
return startups;
}

if (string.IsNullOrEmpty(probingPath) || !Directory.Exists(probingPath))
{
return startups;
}

// Register a permanent handler to resolve assemblies from the probing path.
// This is needed because startup assemblies are loaded into the default ALC
// before the full module loader (LoadContextAssemblyResolver) is configured,
// so their transitive dependencies won't be found otherwise.
// The handler must remain active because startup methods (ConfigureAppConfiguration,
// ConfigureHostServices, etc.) are invoked later during host building and may
// trigger assembly loads at that point.
var fullProbingPath = Path.GetFullPath(probingPath);
AssemblyLoadContext.Default.Resolving += (context, assemblyName) =>
{
var candidatePath = Path.Combine(fullProbingPath, assemblyName.Name + ".dll");
if (File.Exists(candidatePath))
{
return context.LoadFromAssemblyPath(candidatePath);
}

return null;
};

foreach (var manifestFile in Directory.EnumerateFiles(discoveryPath, "module.manifest", SearchOption.AllDirectories))
{
// Exclude manifests from built modules artifacts
if (manifestFile.Contains("artifacts"))
Copy link

Choose a reason for hiding this comment

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

Artifacts path filter checks full path, not relative

Medium Severity

The manifestFile.Contains("artifacts") check tests the entire absolute path, unlike the equivalent code in LocalStorageModuleCatalog.cs which uses manifestFile.Substring(_discoveryPath.Length).Contains("artifacts") to only check the relative portion after the discovery path. If the discovery path itself contains "artifacts" (common in CI/CD pipelines, e.g. /build/artifacts/modules/), every manifest will be skipped and no IPlatformStartup types will be discovered.

Fix in Cursor Fix in Web

{
continue;
}

ModuleManifest manifest;
try
{
manifest = ManifestReader.Read(manifestFile);
}
catch (Exception ex)
{
Console.Error.WriteLine($"Warning: Failed to read module manifest {manifestFile}: {ex.Message}");
continue;
}

if (string.IsNullOrEmpty(manifest?.StartupType) || string.IsNullOrEmpty(manifest.AssemblyFile))
{
continue;
}

var assemblyPath = Path.GetFullPath(Path.Combine(probingPath, manifest.AssemblyFile));
if (!File.Exists(assemblyPath))
{
// Assembly not yet in probing path (first run). Skip gracefully.
continue;
}

try
{
var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);
var startupType = assembly.GetType(manifest.StartupType);

if (startupType == null)
{
// Try partial match (same pattern as ModuleInitializer.TryResolveModuleTypeFromAssembly)
startupType = assembly.GetTypes()
.FirstOrDefault(t => typeof(IPlatformStartup).IsAssignableFrom(t)
&& t.AssemblyQualifiedName?.StartsWith(manifest.StartupType) == true);
}

if (startupType != null
&& typeof(IPlatformStartup).IsAssignableFrom(startupType)
&& Activator.CreateInstance(startupType) is IPlatformStartup startup)
{
startups.Add(startup);
}
else
{
Console.Error.WriteLine(
$"Warning: Startup type '{manifest.StartupType}' in module '{manifest.Id}' does not implement IPlatformStartup or could not be instantiated.");
}
}
catch (Exception ex)
{
Console.Error.WriteLine(
$"Warning: Failed to load startup type '{manifest.StartupType}' from '{manifest.AssemblyFile}' (module '{manifest.Id}'): {ex.Message}");
}
}

return startups.OrderBy(s => s.Priority).ToList();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,6 @@ public static bool IsHttpsServerUrlSet(this IConfiguration configuration)
{
return configuration.TryGetHttpsPort() != PortNotFound;
}

public static bool TryGetAzureAppConfigurationConnectionString(this IConfiguration configuration, out string connectionString)
{
connectionString = configuration.GetConnectionString("AzureAppConfigurationConnectionString");
return !string.IsNullOrWhiteSpace(connectionString);
}
}
}

Loading
Loading