Skip to content

Commit fcbc251

Browse files
committed
[重构]1. 重构启动器
1 parent e3ce8f1 commit fcbc251

File tree

1 file changed

+154
-136
lines changed

1 file changed

+154
-136
lines changed

GameFrameX.Client.Api/Program.cs

Lines changed: 154 additions & 136 deletions
Original file line numberDiff line numberDiff line change
@@ -1,178 +1,196 @@
1+
// GameFrameX 组织下的以及组织衍生的项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
2+
//
3+
// 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE 文件。
4+
//
5+
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
6+
17
using System.Reflection;
2-
using GameFrameX.Client.Api;
38
using GameFrameX.Client.Api.Filter;
49
using GameFrameX.Client.Api.SqlSugar;
510
using GameFrameX.Core.Options;
611
using GameFrameX.Entity;
712
using Microsoft.Extensions.Options;
8-
using Newtonsoft.Json;
9-
using SqlSugar;
10-
11-
var builder = WebApplication.CreateBuilder(args);
13+
using Microsoft.OpenApi.Models;
14+
using Yitter.IdGenerator;
1215

13-
var argsList = builder.Configuration.AsEnumerable().ToList();
16+
namespace GameFrameX.Client.Api;
1417

15-
Console.WriteLine("环境变量开始");
16-
Console.WriteLine(string.Join("\n", argsList));
17-
Console.WriteLine("环境变量结束");
18-
19-
// 处理启动的URLS
20-
List<string> urls = new List<string>();
21-
foreach (string param in args)
18+
/// <summary>
19+
///
20+
/// </summary>
21+
public static class Program
2222
{
23-
string[] ps = param.Split('=');
24-
if (ps.Length > 1)
23+
/// <summary>
24+
///
25+
/// </summary>
26+
/// <param name="args"></param>
27+
public static void Main(string[] args)
2528
{
26-
if (ps[0].Equals("--urls"))
27-
{
28-
urls.AddRange(ps[1].Split(";").ToArray());
29-
}
30-
}
31-
}
29+
var builder = WebApplication.CreateBuilder(args);
3230

33-
LauncherOptions launcherOptions = new LauncherOptions();
31+
var argsList = builder.Configuration.AsEnumerable().ToList();
3432

35-
foreach (var valuePair in argsList)
36-
{
37-
if (valuePair.Key.Equals("DbType"))
38-
{
39-
launcherOptions.DbType = valuePair.Value;
40-
}
41-
else if (valuePair.Key.Equals("ConnectionString"))
42-
{
43-
launcherOptions.ConnectionString = valuePair.Value;
44-
}
45-
}
33+
Console.WriteLine("环境变量开始");
34+
Console.WriteLine(string.Join("\n", argsList));
35+
Console.WriteLine("环境变量结束");
4636

4737

48-
if (urls.Count > 0)
49-
{
50-
builder.WebHost.UseUrls(urls.ToArray());
51-
}
38+
var launcherOptions = InitLauncherOptions(argsList);
5239

53-
// 配置跨域
54-
builder.Services.AddCors((options) =>
55-
{
56-
options.AddPolicy("CorsPolicy", (configurePolicy) =>
57-
{
58-
//允许所有Origin策略
59-
configurePolicy.AllowAnyOrigin()
60-
// 允许任何请求头
61-
.AllowAnyHeader()
62-
// 允许任何请求方法
63-
.AllowAnyMethod().Build();
64-
});
65-
});
66-
var configuration = builder.Configuration.GetSection(nameof(DBConnectionStrings));
67-
builder.Services.Configure<DBConnectionStrings>(configuration);
68-
builder.Services.AddSingleton<DBConnectionStrings>(sp => sp.GetRequiredService<IOptions<DBConnectionStrings>>().Value);
69-
70-
71-
builder.Services
72-
.AddControllers(option => { FilterApp.Init(option.Filters); })
73-
.AddJsonOptions((config) =>
74-
{
75-
// 修改Json 序列化格式为不修改
76-
config.JsonSerializerOptions.PropertyNamingPolicy = null;
77-
});
40+
// 配置雪花ID
41+
var options = new IdGeneratorOptions(0);
42+
YitIdHelper.SetIdGenerator(options);
43+
// 配置跨域
44+
builder.Services.AddCors((options) =>
45+
{
46+
options.AddPolicy("CorsPolicy", (configurePolicy) =>
47+
{
48+
//允许所有Origin策略
49+
configurePolicy.AllowAnyOrigin()
50+
// 允许任何请求头
51+
.AllowAnyHeader()
52+
// 允许任何请求方法
53+
.AllowAnyMethod().Build();
54+
});
55+
});
56+
var configuration = builder.Configuration.GetSection(nameof(DbConnectionStrings));
7857

7958

80-
SqlSugarClient sqlSugar = AddSqlSugarClientService(configuration);
59+
builder.Services.Configure<DbConnectionStrings>(configuration);
60+
builder.Services.AddSingleton<DbConnectionStrings>(sp => sp.GetRequiredService<IOptions<DbConnectionStrings>>().Value);
61+
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
62+
builder.Services.AddHttpClient();
63+
builder.Services
64+
.AddControllers(option => { FilterApp.Init(option.Filters); })
65+
.AddJsonOptions((config) =>
66+
{
67+
// 修改Json 序列化格式为不修改
68+
config.JsonSerializerOptions.PropertyNamingPolicy = null;
69+
});
8170

82-
builder.Services.AddSingleton<ISqlSugarClient>(sqlSugar); // 单例注册
83-
builder.Services.AddScoped(typeof(Repository<>)); // 仓储注册
8471

72+
SqlSugarClient sqlSugar = AddSqlSugarClientService(configuration, launcherOptions);
8573

86-
// 查找实体类.并注册到DI
87-
Assembly assembly = Assembly.GetExecutingAssembly();
88-
foreach (Type type in assembly.GetTypes())
89-
{
90-
if (type.IsInterface)
91-
{
92-
continue;
93-
}
74+
builder.Services.AddSingleton<ISqlSugarClient>(sqlSugar); // 单例注册
75+
builder.Services.AddScoped(typeof(Repository<>)); // 仓储注册
9476

95-
if (type.IsSubclassOf(typeof(BaseController)))
96-
{
97-
ConstructorInfo[] constructorInfos = type.GetConstructors();
98-
foreach (ConstructorInfo constructorInfo in constructorInfos)
77+
78+
// 查找实体类.并注册到DI
79+
Assembly assembly = Assembly.GetExecutingAssembly();
80+
foreach (Type type in assembly.GetTypes())
9981
{
100-
foreach (var parameterInfo in constructorInfo.GetParameters())
82+
if (type.IsInterface)
83+
{
84+
continue;
85+
}
86+
87+
if (type.IsSubclassOf(typeof(BaseController)))
10188
{
102-
if (parameterInfo.ParameterType == typeof(BaseService<>))
89+
ConstructorInfo[] constructorInfos = type.GetConstructors();
90+
foreach (ConstructorInfo constructorInfo in constructorInfos)
10391
{
104-
continue;
92+
foreach (var parameterInfo in constructorInfo.GetParameters())
93+
{
94+
if (parameterInfo.ParameterType == typeof(BaseService<>))
95+
{
96+
continue;
97+
}
98+
99+
builder.Services.AddScoped(parameterInfo.ParameterType);
100+
}
105101
}
106-
107-
builder.Services.AddScoped(parameterInfo.ParameterType);
108102
}
109103
}
110-
}
111-
}
112104

113105

114-
AddSwaggerService(builder.Services);
106+
AddSwaggerService(builder.Services);
115107

116-
var app = builder.Build();
108+
var app = builder.Build();
117109

118110
// Configure the HTTP request pipeline.
119-
if (app.Environment.IsDevelopment())
120-
{
121-
// app.UseSwagger();
122-
// app.UseSwaggerUI();
123-
}
111+
if (app.Environment.IsDevelopment())
112+
{
113+
app.UseSwagger();
114+
app.UseSwaggerUI();
115+
}
116+
124117
// app.UseHttpsRedirection();
125-
app.MapControllers();
118+
app.MapControllers();
126119
// 设置跨域
127-
app.UseCors("CorsPolicy");
128-
app.Run();
120+
app.UseCors("CorsPolicy");
121+
app.Run();
122+
}
129123

130-
void AddSwaggerService(IServiceCollection service)
131-
{
132-
// Add services to the container.
133-
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
134-
service.AddEndpointsApiExplorer();
135-
// service.AddSwaggerGen(swaggerGenOptions =>
136-
// {
137-
// swaggerGenOptions.SwaggerDoc("v1", new OpenApiInfo { Title = "HTTP.ClientApi", Version = "v1" });
138-
//
139-
// DirectoryInfo directoryInfo = new DirectoryInfo(AppContext.BaseDirectory);
140-
// var fileList = directoryInfo.GetFiles("*.xml", SearchOption.AllDirectories);
141-
// foreach (FileInfo fileInfo in fileList)
142-
// {
143-
// swaggerGenOptions.IncludeXmlComments(fileInfo.FullName, true);
144-
// }
145-
//
146-
// swaggerGenOptions.OrderActionsBy(s => s.RelativePath);
147-
// });
148-
}
149-
150-
SqlSugarClient AddSqlSugarClientService(IConfigurationSection configurationSection)
151-
{
152-
//Scoped用SqlSugarClient
153-
var dbConfig = new ConnectionConfig()
124+
private static LauncherOptions InitLauncherOptions(List<KeyValuePair<string, string>> argsList)
154125
{
155-
DbType = Enum.Parse<SqlSugar.DbType>(!string.IsNullOrWhiteSpace(launcherOptions.DbType) ? launcherOptions.DbType : (configurationSection["DbType"] ?? SqlSugar.DbType.Sqlite.ToString())),
156-
ConnectionString = !string.IsNullOrWhiteSpace(launcherOptions.ConnectionString) ? launcherOptions.ConnectionString : configurationSection["ConnectionString"],
157-
IsAutoCloseConnection = true,
158-
};
159-
160-
Console.WriteLine(JsonConvert.SerializeObject(dbConfig));
161-
SqlSugarClient sqlSugarClient = new SqlSugarClient(dbConfig,
162-
db =>
126+
LauncherOptions launcherOptions = null;
127+
foreach (var keyValuePair in argsList)
163128
{
164-
//每次上下文都会执行
129+
if (keyValuePair.Key == "DbType")
130+
{
131+
if (launcherOptions == null)
132+
{
133+
launcherOptions = new LauncherOptions();
134+
}
135+
136+
launcherOptions.DbType = keyValuePair.Value;
137+
}
138+
else if (keyValuePair.Key == "ConnectionString")
139+
{
140+
if (launcherOptions == null)
141+
{
142+
launcherOptions = new LauncherOptions();
143+
}
165144

166-
//获取IOC对象不要求在一个上下文
167-
//vra log=s.GetService<Log>()
145+
launcherOptions.ConnectionString = keyValuePair.Value;
146+
}
147+
}
148+
149+
return launcherOptions;
150+
}
151+
152+
private static void AddSwaggerService(IServiceCollection service)
153+
{
154+
service.AddEndpointsApiExplorer();
155+
service.AddSwaggerGen(swaggerGenOptions =>
156+
{
157+
swaggerGenOptions.SwaggerDoc("v1", new OpenApiInfo { Title = "GameFrameX.Admin.Client.Api", Version = "v1" });
168158

169-
//获取IOC对象要求在一个上下文
170-
//var appServive = s.GetService<IHttpContextAccessor>();
171-
//var log= appServive?.HttpContext?.RequestServices.GetService<Log>();
159+
DirectoryInfo directoryInfo = new DirectoryInfo(AppContext.BaseDirectory);
160+
var fileList = directoryInfo.GetFiles("*.xml", SearchOption.AllDirectories);
161+
foreach (FileInfo fileInfo in fileList)
162+
{
163+
swaggerGenOptions.IncludeXmlComments(fileInfo.FullName, true);
164+
}
172165

173-
db.Aop.OnLogExecuting = (sql, pars) => { };
174-
// 配置软删除过滤器
175-
db.QueryFilter.AddTableFilter<IDeletedFilter>(u => u.IsDelete == false);
166+
swaggerGenOptions.OrderActionsBy(s => s.RelativePath);
176167
});
177-
return sqlSugarClient;
168+
}
169+
170+
/// <summary>
171+
/// 添加SqlSugar
172+
/// </summary>
173+
/// <param name="configurationSection"></param>
174+
/// <param name="launcherOptions"></param>
175+
/// <returns></returns>
176+
static SqlSugarClient AddSqlSugarClientService(IConfigurationSection configurationSection, LauncherOptions launcherOptions)
177+
{
178+
var dbConfig = new ConnectionConfig()
179+
{
180+
DbType = Enum.Parse<global::SqlSugar.DbType>(!string.IsNullOrWhiteSpace(launcherOptions.DbType) ? launcherOptions.DbType : (configurationSection["DbType"] ?? global::SqlSugar.DbType.Sqlite.ToString())),
181+
ConnectionString = !string.IsNullOrWhiteSpace(launcherOptions.ConnectionString) ? launcherOptions.ConnectionString : configurationSection["ConnectionString"],
182+
IsAutoCloseConnection = true,
183+
};
184+
185+
Console.WriteLine("数据库配置信息");
186+
Console.WriteLine(JsonConvert.SerializeObject(dbConfig, Formatting.Indented));
187+
Console.WriteLine();
188+
SqlSugarClient sqlSugarClient = new SqlSugarClient(dbConfig,
189+
db =>
190+
{
191+
// 配置软删除过滤器
192+
db.QueryFilter.AddTableFilter<IDeletedFilter>(u => u.IsDelete == false);
193+
});
194+
return sqlSugarClient;
195+
}
178196
}

0 commit comments

Comments
 (0)