Rewrite host to use standard hosting patterns

This commit is contained in:
Matija Koželj 2023-01-04 15:24:41 +01:00
parent c5c6ac4a72
commit c67b11eec3

View File

@ -1,67 +1,42 @@
using System.Reflection;
using Connected.Host.Configuration; using Connected.Host.Configuration;
namespace Connected.Host namespace Connected.Host
{ {
public static class Program public static partial class Program
{ {
public static void Main(params string[] args) public static async Task Main(params string[] args)
{ {
SysConfiguration.Build(); using IHost host = Microsoft.Extensions.Hosting.Host
.CreateDefaultBuilder(args)
Start(ParseArguments(args)); .ConfigureAppConfiguration((_, cfg) =>
}
private static void Start(Dictionary<string, string> args)
{ {
foreach (var microService in SysConfiguration.MicroServices) var appPath = AppContext.BaseDirectory;
LoadMicroServiceAssembly(microService); var segments = new Uri(appPath).Segments;
if (Type.GetType(SysConfiguration.Start) is not Type startupType) segments = segments.Select(e => e.Replace("%20", " ")).ToArray();
throw new Exception($"Cannot resolve startup type. ({SysConfiguration.Start}).");
if (startupType.GetMethod("ConfigureAsync", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) is not MethodInfo configureMethod) for (var i = 1; i <= segments.Length; i++)
throw new Exception($"ConfigureAsync does not exists in the startup type {startupType}. Startup must have static 'async Task ConfigureAsync(params string[] args)' method.");
if (configureMethod.Invoke(null, new object[] { args }) is not Task task)
throw new Exception($"ConfigureAsync of type {startupType} must return Task.");
task.ConfigureAwait(false);
task.GetType().GetProperty("Result")?.GetValue(task);
}
private static Assembly? LoadMicroServiceAssembly(MicroServiceDescriptor descriptor)
{ {
var assemblyFile = descriptor.Name.EndsWith(".dll") ? descriptor.Name : $"{descriptor.Name}.dll"; var pathBase = Path.Combine(segments[0..i]);
var filePath = Path.Combine(pathBase, "sys.json");
foreach (var location in SysConfiguration.Locations) if (File.Exists(filePath))
{ {
var assemblyPath = Path.Combine(location, assemblyFile); cfg.AddJsonFile(filePath, true, false);
break;
if (File.Exists(assemblyPath)) }
return Assembly.LoadFrom(assemblyPath);
} }
return Assembly.Load(AssemblyName.GetAssemblyName(assemblyFile)); cfg.AddEnvironmentVariables();
} })
.ConfigureServices((context, services) =>
private static Dictionary<string, string> ParseArguments(params string[] args)
{ {
var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); services.Configure<SysConfiguration>(context.Configuration);
services.AddHostedService<ConnectedPlatformService>();
foreach (var i in args) })
{ .Build();
var tokens = i.Split('=', 2);
if (tokens.Length == 1)
result.Add(tokens[0].Trim(), string.Empty);
else
result.Add(tokens[0].Trim(), tokens[1].Trim());
}
return result;
}
await host.RunAsync();
}
} }
} }