Abp每一个项目都是模块,按模块开发,模块依赖型的
[DependsOn] (依赖)
Abp的核心就是模块依赖
namespace AbpDemo
{
[DependsOn(typeof(AbpAspNetCoreMvcModule))]
public class AbpDemoModule:AbpModule
{
/// <summary>
/// 服务依赖注入
/// </summary>
/// <param name="context"></param>
public override void ConfigureServices(ServiceConfigurationContext context)
{
base.ConfigureServices(context);
}
/// <summary>
/// 中间件配置
/// </summary>
/// <param name="context"></param>
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
base.OnApplicationInitialization(context);
}
}
}
2.把启动类里面的依赖注入builder.Services.XXX转移到模块类的ConfigureServices
3.把启动类的app.UseXXX使用中间件等代码转移到OnApplicationInitialization
调整完后Program.cs启动类变成
using AbpDemo;
var builder = WebApplication.CreateBuilder(args);
// 重新注册 Configuration 不加启动会报错
builder.Services.ReplaceConfiguration(builder.Configuration);
//添加自定义模块
builder.Services.AddApplication<AbpDemoModule>();
//* 同上等效代码
//* 添加自定义模块 DemoWebApiModule
//builder.Services.AddApplication<DemoWebApiModule>(options => {
//options.Services.ReplaceConfiguration(builder.Configuration); // 重新注册 Configuration
//});
var app = builder.Build();
app.InitializeApplication();
app.Run();
Module类:
using Volo.Abp;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Modularity;
namespace AbpDemo
{
[DependsOn(
typeof(AbpAspNetCoreMvcModule),
typeof(AbpAutofacModule)
)]
public class AbpDemoModule : AbpModule
{
/// <summary>
/// 服务依赖注入
/// </summary>
/// <param name="context"></param>
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddControllersWithViews();
}
/// <summary>
/// 中间件配置
/// </summary>
/// <param name="context"></param>
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
var app = context.GetApplicationBuilder();
if (!context.GetEnvironment().IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(
end =>
{
end.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
);
}
);
}
}
}
项目启动即可
扫描二维码,在手机上阅读!
评论