|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
|
using System.Reflection;
|
|
|
|
|
|
|
|
|
|
namespace Ds.Module.AppStartup
|
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
///
|
|
|
|
|
/// </summary>
|
|
|
|
|
[AttributeUsage(AttributeTargets.Class)]
|
|
|
|
|
public class Ds_StartupAttribute : Attribute
|
|
|
|
|
{ }
|
|
|
|
|
|
|
|
|
|
public interface IDs_App_Startup
|
|
|
|
|
{
|
|
|
|
|
void ConfigureServices(IServiceCollection services);
|
|
|
|
|
|
|
|
|
|
void Configure(object app);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
///
|
|
|
|
|
/// </summary>
|
|
|
|
|
public static class Ds_App_Startup
|
|
|
|
|
{
|
|
|
|
|
public static void Run()
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var startupTypes = Assembly.GetCallingAssembly().GetTypes()
|
|
|
|
|
.Where(type => type.GetCustomAttribute<Ds_StartupAttribute>() != null);
|
|
|
|
|
|
|
|
|
|
var services = new ServiceCollection();
|
|
|
|
|
|
|
|
|
|
foreach (var startupType in startupTypes)
|
|
|
|
|
{
|
|
|
|
|
var startupInstance = Activator.CreateInstance(startupType) as IDs_App_Startup;
|
|
|
|
|
startupInstance?.ConfigureServices(services);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 构建 IServiceProvider
|
|
|
|
|
var serviceProvider = services.BuildServiceProvider();
|
|
|
|
|
|
|
|
|
|
foreach (var startupType in startupTypes)
|
|
|
|
|
{
|
|
|
|
|
var startupInstance = Activator.CreateInstance(startupType);
|
|
|
|
|
var configureMethod = startupType.GetMethod("Configure");
|
|
|
|
|
|
|
|
|
|
if (configureMethod != null)
|
|
|
|
|
{
|
|
|
|
|
configureMethod.Invoke(startupInstance, new[] { serviceProvider });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
// 友好的错误消息和日志记录
|
|
|
|
|
Console.WriteLine($"An error occurred: {ex.Message}");
|
|
|
|
|
// 日志记录
|
|
|
|
|
// Logger.LogError(ex, "An error occurred during startup.");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//// 示例启动类
|
|
|
|
|
//[MyFrameworkStartup]
|
|
|
|
|
//public class MyFrameworkStartup : IMyFrameworkStartup
|
|
|
|
|
//{
|
|
|
|
|
// public void ConfigureServices(IServiceCollection services)
|
|
|
|
|
// {
|
|
|
|
|
// // 配置服务
|
|
|
|
|
// services.AddTransient<IMyService, MyService>();
|
|
|
|
|
// // 其他服务配置...
|
|
|
|
|
// }
|
|
|
|
|
|
|
|
|
|
// public void Configure(object app)
|
|
|
|
|
// {
|
|
|
|
|
// // 配置中间件
|
|
|
|
|
// // 其他中间件配置...
|
|
|
|
|
// }
|
|
|
|
|
//}
|
|
|
|
|
|
|
|
|
|
// 示例服务
|
|
|
|
|
//public interface IMyService
|
|
|
|
|
//{
|
|
|
|
|
// void DoSomething();
|
|
|
|
|
//}
|
|
|
|
|
|
|
|
|
|
//public class MyService : IMyService
|
|
|
|
|
//{
|
|
|
|
|
// public void DoSomething()
|
|
|
|
|
// {
|
|
|
|
|
// Console.WriteLine("Doing something...");
|
|
|
|
|
// }
|
|
|
|
|
//}
|
|
|
|
|
|
|
|
|
|
//internal class Program
|
|
|
|
|
//{
|
|
|
|
|
// private static void Main()
|
|
|
|
|
// {
|
|
|
|
|
// MyFramework.Run();
|
|
|
|
|
// }
|
|
|
|
|
//}
|
|
|
|
|
}
|