Dipper/Dipper.Alioth/Extensions/StarletExtension.cs

65 lines
1.9 KiB
C#

namespace Dipper.Alioth.Extensions;
public static class StarletExtension
{
public static WebApplicationBuilder AddStarApp(this WebApplicationBuilder builder, Action<StarOption>? action = null)
{
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
var option = new StarOption();
action?.Invoke(option);
builder.Services.AddControllers(options =>
{
options.EnableEndpointRouting = false;
option.MvcOption?.Invoke(options);
})
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
option.JsonOption?.Invoke(options);
})
.AddFlexibleApi(option);
return builder;
}
public static WebApplication UseStarApp(this WebApplication app)
{
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseRouting();
app.MapControllers();
return app;
}
/// <summary>
/// 添加动态接口
/// </summary>
/// <param name="builder"></param>
/// <param name="option"></param>
private static void AddFlexibleApi(this IMvcBuilder builder, StarOption option)
{
builder.ConfigureApplicationPartManager(manager =>
{
manager.ApplicationParts.Add(new AssemblyPart(typeof(IStarlet).Assembly));
foreach (var module in option.Asterisms)
{
module.Initialize();
var assembly = module.GetType().Assembly;
manager.ApplicationParts.Add(new AssemblyPart(assembly));
}
manager.FeatureProviders.Add(new Providers.StarletFeatureProvider());
});
builder.Services.Configure<MvcOptions>(options =>
{
options.Conventions.Add(new StarletConvention());
});
}
}